Activation error occured while trying to get instance of type LogWriter, key ""

Topics: Logging Application Block
Dec 22, 2010 at 5:26 AM
Edited Dec 22, 2010 at 5:34 AM

 am trying to create a logging domain service for my project which makes use of Silverlight, RIA Services and EF. To log errors in domain services, I created a Logging Domain service and it has the following declaration

Option Compare Binary
Option Infer On
Option Strict On
Option Explicit On

Imports myProject.Web
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Imports System.Data
Imports System.Linq
Imports System.ServiceModel.DomainServices.EntityFramework
Imports System.ServiceModel.DomainServices.Hosting
Imports System.ServiceModel.DomainServices.Server

Imports Microsoft.Practices.EnterpriseLibrary.Common.Configuration
Imports Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity
Imports Microsoft.Practices.EnterpriseLibrary.Logging
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Filters
Imports Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation
Imports Microsoft.Practices.Unity





' TODO: Add your application logic to these methods or in additional methods.
' TODO: Wire up authentication (Windows/ASP.NET Forms) and uncomment the following to disable anonymous access
' Also consider adding roles to restrict access as appropriate.
'<RequiresAuthentication> _
<EnableClientAccess()> _
Public Class LoggingDomainService
    Inherits LinqToEntitiesDomainService(Of MyDatabaseEntities)


    Shared myLogWriter As LogWriter

  
    <Invoke()>
    Public Sub WriteLog(ByVal ex As String)
        Try
            myLogWriter.Write(ex, "General")
        Catch ex1 As Exception
            Throw New Exception(ex1.Message)
        End Try

    End Sub

    Public Sub New()
        Dim myContainer As New UnityContainer()
        Dim myConfigureContainer As New UnityContainerConfigurator(myContainer)
        EnterpriseLibraryContainer.ConfigureContainer(myConfigureContainer, New FileConfigurationSource("C:\Projects\MyWeb\Development\Software\WebTesting\WebTesting.Web\web.config"))
        myLogWriter = myContainer.Resolve(Of LogWriter)()


    End Sub
End Class

Initially when I did not have the constructor, I was getting the error 
Activation error occured while trying to get instance of type LogWriter, key ""
After looking at other posts which suggested to resolve the container, I inserted the contructor. Now I am getting this error. 

Resolution of the dependency failed, type = "Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type Database cannot be constructed. You must configure the container to supply this value.
-----------------------------------------------
At the time of the exception, the container was:

  Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterImpl,LogWriter.__default__ (mapped from Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter, (none))
  Resolving parameter "structureHolder" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterImpl(Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder structureHolder, Microsoft.Practices.EnterpriseLibrary.Logging.Instrumentation.ILoggingInstrumentationProvider instrumentationProvider, Microsoft.Practices.EnterpriseLibrary.Logging.ILoggingUpdateCoordinator updateCoordinator)
    Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder,LogWriterStructureHolder.__default__ (mapped from Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder, (none))
    Resolving parameter "traceSources" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder(System.Collections.Generic.IEnumerable`1[[Microsoft.Practices.EnterpriseLibrary.Logging.Filters.ILogFilter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] filters, System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] traceSourceNames, System.Collections.Generic.IEnumerable`1[[Microsoft.Practices.EnterpriseLibrary.Logging.LogSource, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] traceSources, Microsoft.Practices.EnterpriseLibrary.Logging.LogSource allEventsTraceSource, Microsoft.Practices.EnterpriseLibrary.Logging.LogSource notProcessedTraceSource, Microsoft.Practices.EnterpriseLibrary.Logging.LogSource errorsTraceSource, System.String defaultCategory, System.Boolean tracingEnabled, System.Boolean logWarningsWhenNoCategoriesMatch, System.Boolean revertImpersonation)
      Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogSource,General
      Resolving parameter "traceListeners" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.LogSource(System.String name, System.Collections.Generic.IEnumerable`1[[System.Diagnostics.TraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] traceListeners, System.Diagnostics.SourceLevels level, System.Boolean autoFlush, Microsoft.Practices.EnterpriseLibrary.Logging.Instrumentation.ILoggingInstrumentationProvider instrumentationProvider)
        Resolving Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.ReconfigurableTraceListenerWrapper,Database Trace Listener (mapped from System.Diagnostics.TraceListener, Database Trace Listener)
        Resolving parameter "wrappedTraceListener" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.ReconfigurableTraceListenerWrapper(System.Diagnostics.TraceListener wrappedTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.ILoggingUpdateCoordinator coordinator)
          Resolving Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener,Database Trace Listener‌implementation (mapped from System.Diagnostics.TraceListener, Database Trace Listener‌implementation)
          Resolving parameter "database" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener(Microsoft.Practices.EnterpriseLibrary.Data.Database database, System.String writeLogStoredProcName, System.String addCategoryStoredProcName, Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.ILogFormatter formatter)
            Resolving Microsoft.Practices.EnterpriseLibrary.Data.Database,MyDatabaseEntities
It seems that it is unable to connect the database or read the connection strings from the web.config.
My web.config is below
 
    
  
  
    
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>
  <loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="General">
    <listeners>
      <add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" source="Logging" formatter="Text Formatter" log="EventLog" machineName="." traceOutputOptions="None" />
      <add name="Database Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" databaseInstanceName="MyDatabaseEntities" writeLogStoredProcName="LoggingWriteLog" addCategoryStoredProcName="LoggingAddCategory" formatter="Text Formatter" />
      <add name="Email Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.EmailTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.EmailTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" toAddress="to@to.com" fromAddress="noreply@to.com" subjectLineStarter="**Error**" smtpServer="xxxxxxxxx" formatter="Text Formatter" />
      <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" fileName="c:\LogFile.log" formatter="Text Formatter" rollInterval="Midnight" rollSizeKB="0" traceOutputOptions="None" />
    </listeners>
    <formatters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}" name="Text Formatter" />
    </formatters>
    <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="Event Log Listener" />
          <add name="Database Trace Listener" />
          <add name="Email Trace Listener" />
          <add name="Rolling Flat File Trace Listener" />
        </listeners>
      </add>
    </categorySources>
    <specialSources>
      <allEvents switchValue="Critical" name="All Events">
        <listeners>
          <add name="Email Trace Listener" />
          <add name="Event Log Listener" />
          <add name="Rolling Flat File Trace Listener" />
        </listeners>
      </allEvents>
      <notProcessed switchValue="All" name="Unprocessed Category">
        <listeners>
          <add name="Rolling Flat File Trace Listener" />
          <add name="Email Trace Listener" />
        </listeners>
      </notProcessed>
      <errors switchValue="All" name="Logging Errors &amp; Warnings">
        <listeners>
          <add name="Event Log Listener" />
          <add name="Database Trace Listener" />
          <add name="Email Trace Listener" />
          <add name="Rolling Flat File Trace Listener" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>
  <dataConfiguration defaultDatabase="MyDatabaseEntities" />
  <connectionStrings>
    <add name="MyDatabaseEntities" connectionString="metadata=res://*/AppData.MyDatabase.csdl|res://*/AppData.MyDatabase.ssdl|res://*/AppData.MyDatabase.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=mydatabaseserver;Initial Catalog=myWebDB;Persist Security Info=True;User ID=user;Password=password;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="DomainServiceModule" preCondition="managedHandler" type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </modules>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <system.web>
    <authentication mode="Forms" />
    <httpModules>
      <add name="DomainServiceModule" type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </httpModules>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
</configuration>
What am I doing wrong? Is Ent Lib 5.0 not supported with EF 4?
Regards,Arpan

 

Dec 22, 2010 at 7:07 AM

If you try to call

 DbProviderFactory providerFactory = DbProviderFactories.GetFactory("System.Data.EntityClient");

is it successful or are you getting an exception?

 

Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com

Dec 22, 2010 at 7:47 AM

The answer is no, Entlib 5.0 cannot use Entity Framework to access a database. Entlib has been around a LOT longer than EF has, and there was no benefit in rewriting Entlib to use EF, particularly for something that just called a predefined stored procedure..

The easiest thing to do is add a second connection string, using plain ADO.NET as opposed to EF, that points to the same database.

 

Dec 22, 2010 at 12:55 PM

Thanks for the clarification. I created the second connection string using plain ADO.NET for Entlib and it worked(Sarah to answer your question -- I tried your suggestion and an error occurred saying that the

type could not be found).

Thanks for your guidance.


Arpan

Mar 1, 2011 at 8:18 PM

Hi Sarah,
I am getting the below error:

Activation error occured while trying to get instance of type Database, key "MYDatabaseInstance"

MY CONFIG LOOKS LIKE:

<configuration>
    <configSections>
        <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <dataConfiguration defaultDatabase="Connection String" />
    <connectionStrings>      
        <add name="MYDatabaseInstance" connectionString="Database=DB2DB;User ID=ASDF;Password=ASFDSAFD;Server=SAFDSAFD:50200;Persist Security Info=True;CurrentSchema=GHTR;Connect Timeout=0;&quot;"
            providerName="IBM.Data.DB2" />
    </connectionStrings>
</configuration>


MY CODE LOOKS LIKE:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging;
using RxCExceptionHandler;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using IBM.Data.DB2;


   try
            {
              //  Database myDB = EnterpriseLibraryContainer.Current.GetInstance<Database>();
                Database myDB = DatabaseFactory.CreateDatabase("RxCDatabaseInstance");

                IDataReader dbReader = myDB.ExecuteReader(CommandType.Text, "SELECT COUNT(*) FROM GHTR.RXC_JOB ");
                while (dbReader.Read())
                {
                    MessageBox.Show(dbReader[1].ToString());
 
                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }


Please help !!!!

Mar 2, 2011 at 9:10 AM

Hi,

I think you forgot to add the "providerMappings" node within the dataConfiguration node. Also, I assume your default db is named "MYDatabaseInstance" so the value for the defaultDatabase is "MyDatabaseInstance" and not "Connection String". Your configuration will more or less look like this:

<configuration>
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>
  <dataConfiguration defaultDatabase="MYDatabaseInstance">
    <providerMappings>
      <add databaseType="[Class Name],[Assembly Title], [Assembly Version], [Assembly Culture], [PublicKeyToken]"
          name="[Name of Custom DB Provider]" />
    </providerMappings>
  </dataConfiguration>
  <connectionStrings>
    <add name="MYDatabaseInstance" connectionString="Database=DB2DB;User ID=ASDF;Password=ASFDSAFD;Server=SAFDSAFD:50200;Persist Security Info=True;CurrentSchema=GHTR;Connect Timeout=0;&quot;"
        providerName="IBM.Data.DB2" />
  </connectionStrings>
</configuration>

Mar 2, 2011 at 3:37 PM

Thanks daaberkads,

But I am still getting the same error. Here is the code and the config.  Need urgent help..... I am using .NET Framework 4.0 and Enterprise Library 5.0.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging;
using RxCExceptionHandler;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using IBM.Data.DB2;

try
            {
              //  Database myDB = EnterpriseLibraryContainer.Current.GetInstance<Database>();
                Database myDB = DatabaseFactory.CreateDatabase("MyDatabaseInstance");

                IDataReader dbReader = myDB.ExecuteReader(CommandType.Text, "SELECT COUNT(*) FROM JOB ");
                while (dbReader.Read())
                {
                    MessageBox.Show(dbReader[1].ToString());
 
                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }

 

 

<configuration>
    <configSections>
        <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
  <dataConfiguration defaultDatabase="MyDatabaseInstance">
    <providerMappings>
      <add databaseType="Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="IBM.Data.DB2" />
    </providerMappings>
  </dataConfiguration>
    <connectionStrings>
      <add name="MyDatabaseInstance" connectionString="Database=DB2DB;User ID=abc;Password=xyz;Server=ssss:sssss;Persist Security Info=True;CurrentSchema=MY_SCHEMA;Connect Timeout=0;"
          providerName="IBM.Data.DB2" />
    </connectionStrings> 
</configuration>

 

Mar 3, 2011 at 3:43 AM

Hi,

I forgot to say that you need to create a custom database provider for DB2, which you will define inside the providerMappings.  I have a sample solution here. If you like, you can send me your email so I can send to you the solution files.

Regards,

 

Mar 3, 2011 at 3:52 PM

I tried that earlier but it didnt work. I am still getting the same error.

 

InnerException = {"Resolution of the dependency failed, type = \"Microsoft.Practices.EnterpriseLibrary.Data.Database\", name = \"RxCDatabaseInstance\".\r\nException occurred while: while resolving.\r\nException is: InvalidOperationException - The type Database cannot be con...

Message = "The type Database cannot be constructed. You must configure the container to supply this value."

 

My Email ID: thynameisrahul@gmail.com. Please send your sample solution on this email.

Mar 4, 2011 at 1:50 AM
Edited Mar 4, 2011 at 1:59 AM

Hi Rahul,

The idea is to create a wrapper for DB2 provider and define it inside the providerMappings. For example you have a wrapper named DB2Database, your config will look like this:

 <providerMappings>
      <add databaseType="CustomDatabaseProvider.DB2Database, CustomDatabaseProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="IBM.Data.DB2" />
  </providerMappings>

Also, register the DB2 provider to your config. It will look like this:

 <system.data>
  <DbProviderFactories>
   <add name="IBM DB2 .NET Data Provider" invariant="IBM.Data.DB2" description="IBM DB2 Data Provider for .NET Framework 2.0" type="IBM.Data.DB2.DB2Factory, IBM.Data.DB2, Version=9.0.0.2, Culture=neutral, PublicKeyToken=7c307b91aa13d208" />
  </DbProviderFactories>
 </system.data>

I already send you the solution file. Kindly refer to the App.config of CustomDatabaseProvider.Host. If you have further questions, just let me know. :)

Mar 4, 2011 at 8:22 PM

Thanks So much daaberkads but I am still getting this error.

 

Message = "Could not load file or assembly 'CustomDatabaseProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7c307b91aa13d208' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESUL...

Mar 7, 2011 at 2:21 AM

Make sure you are referencing the correct dll. If you made some changes in 'CustomDatabaseProvider', be sure your project is properly referencing to the latest version of it.