| 

.NET C# Java Javascript Exception

3
Hallo zusammen.

Ich spiele gerade ein wenig mit der Microsoft Enterprise Library rum bin auf ein Problem gestossen bei der Konfiguration des Logging Application Blocks per fluent configuration API.

Wenn ich die Konfiguration per Wizard mache funktioniert es ohne Probleme. Jetzt versuche ich die Konfiguration zur Laufzeit zu erstellen und hier bekomme ich eine Exception und ich finde das Problem nicht.

Hier zunächst die Konfiguration aus den App.config mit der der Code funktioniert.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="General Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="d:\x_general.log" formatter="Text Formatter" />
<add name="All Events Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="D:\x_all.log" formatter="Text Formatter" />
<add name="Unprocessed Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="d:\unprocess.log" formatter="Text Formatter" />
<add name="Error Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="d:\error.log" formatter="Text Formatter" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="Timestamp: {timestamp(local)}&#xA;Message: {message}&#xA;Category: {category}&#xA;Priority: {priority}&#xA;Event ID: {eventid}&#xA;Severity: {severity}&#xA;"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="General Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events">
<listeners>
<add name="All Events Listener" />
</listeners>
</allEvents>
<notProcessed switchValue="All" name="Unprocessed Category">
<listeners>
<add name="Unprocessed Listener" />
</listeners>
</notProcessed>
<errors switchValue="All" name="Logging Errors &amp; Warnings">
<listeners>
<add name="Error Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
</configuration>


Und hier jetzt mein Code, den ich zum Testen verwendet habe:
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.Unity;

namespace LoggingDemo
{
public class Logging : ILsmLogging
{
private readonly IUnityContainer _container;
private readonly LogWriter _logWriter;

public Logging()
{
CreateLoggingConfiguration();

_container = new UnityContainer().AddNewExtension<EnterpriseLibraryCoreExtension>();
_logWriter = _container.Resolve<LogWriter>();
}
public void Log(string text, string category = "General", int eventId = 3000, int priority = 1, TraceEventType type = TraceEventType.Verbose, string title = "LSM Log Entry")
{
_logWriter.Write(text, category, priority, eventId, type, title);
}

private void CreateLoggingConfiguration()
{
var formatBuilder = new FormatterBuilder()
.TextFormatterNamed("Text Formatter")
.UsingTemplate("Timestamp: {timestamp(local)}&#xA;Message: {message}&#xA;Category: {category}&#xA;Priority: {priority}&#xA;Event ID: {eventid}&#xA;Severity: {severity}&#xA;");


var builder = new ConfigurationSourceBuilder();

builder.ConfigureLogging()
.WithOptions
.LogToCategoryNamed("General")
.WithOptions
.SetAsDefaultCategory()
.SendTo
.FlatFile("General Trace Listener")
.FormatWith(formatBuilder)
.ToFile(@"d:\x_general.log")
.SpecialSources
.AllEventsCategory
.SendTo
.FlatFile("All Events Listener")
.FormatWith(formatBuilder)
.ToFile(@"d:\x_all.log")
.SpecialSources
.UnprocessedCategory
.SendTo
.FlatFile("Unprocessed Listener")
.FormatWith(formatBuilder)
.ToFile(@"d:\x_unprocessed.log")
.SpecialSources
.LoggingErrorsAndWarningsCategory
.SendTo
.FlatFile("Error Listener")
.FormatWith(formatBuilder)
.ToFile(@"d:\error.log");


var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
}
}

public interface ILsmLogging
{
void Log(string text, string category = "General", int eventId = 3000, int priority = 1, TraceEventType type = TraceEventType.Verbose, string title = "LSM Log Entry");
}
}


Die Exception tritt auf, wenn im Konstruktor die Resolve Methode aufgerufen wird.
Hier die Exception:
Microsoft.Practices.Unity.ResolutionFailedException was unhandled
Message=Resolution of the dependency failed, type = "Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type LogWriter 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.LogWriter,(none)

Source=Microsoft.Practices.Unity
TypeRequested=LogWriter
StackTrace:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)
at LoggingDemo.Logging..ctor() in D:\Users\multhaupj\Documents\Visual Studio 2010\Projects\LoggingDemoTest\LoggingDemo\Logging.cs:line 19
at LoggingDemoClient.Program.Main(String[] args) in D:\Users\multhaupj\Documents\Visual Studio 2010\Projects\LoggingDemoTest\LoggingDemoClient\Program.cs:line 13
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.InvalidOperationException
Message=The type LogWriter cannot be constructed. You must configure the container to supply this value.
Source=Microsoft.Practices.Unity
StackTrace:
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.GuardTypeIsNonPrimitive(IBuilderContext context, SelectedConstructor selectedConstructor)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlanCreatorPolicy.CreatePlan(IBuilderContext context, NamedTypeBuildKey buildKey)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
InnerException:


Hat jemand eine Idee was hier falsch ist??

Vielen Dank schon mal im voraus.

Jörg
News:
01.06.2012
multi1209 848 1 8
Ist EnterpriseLibrary nicht total veraltet? Z.b. Unity wurde doch schon vor Jahren in einem separaten Projekt fortgeführt und der Rest wurde zu Recht aufgegeben
kleffel 05.06.2012
1 Antwort
1
Hallo Jörg,

Du hast einfach nur vergessen den Container zu konfigurieren.

Hier ist der von mir überarbeitete Sourcecode.
Geänderte/neue Codezeilen habe ich fett formatiert.

using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.Unity;

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity;


namespace LoggingDemo
{
public class Logging : ILsmLogging
{
private readonly IUnityContainer _container;
private readonly LogWriter _logWriter;

private IContainerConfigurator _configurator;

public Logging()
{

_container = new UnityContainer().AddNewExtension<EnterpriseLibraryCoreExtension>();
_configurator = new UnityContainerConfigurator(_container);

CreateLoggingConfiguration();
_logWriter = _container.Resolve<LogWriter>();

}

public void Log(string text, string category = "General", int eventId = 3000, int priority = 1, TraceEventType type = TraceEventType.Verbose, string title = "LSM Log Entry")
{
_logWriter.Write(text, category, priority, eventId, type, title);
}

private void CreateLoggingConfiguration()
{
var formatBuilder = new FormatterBuilder()
.TextFormatterNamed("Text Formatter")
.UsingTemplate("Timestamp: {timestamp(local)}&#xA;Message: {message}&#xA;Category: {category}&#xA;Priority: {priority}&#xA;Event ID: {eventid}&#xA;Severity: {severity}&#xA;");


var builder = new ConfigurationSourceBuilder();

builder.ConfigureLogging()
.WithOptions
.LogToCategoryNamed("General")
.WithOptions
.SetAsDefaultCategory()
.SendTo
.FlatFile("General Trace Listener")
.FormatWith(formatBuilder)
.ToFile(@"C:\Projects\PowerShell\codekick2\codekick2\x_general.log")
.SpecialSources
.AllEventsCategory
.SendTo
.FlatFile("All Events Listener")
.FormatWith(formatBuilder)
.ToFile(@"C:\Projects\PowerShell\codekick2\codekick2\x_all.log")
.SpecialSources
.UnprocessedCategory
.SendTo
.FlatFile("Unprocessed Listener")
.FormatWith(formatBuilder)
.ToFile(@"C:\Projects\PowerShell\codekick2\codekick2\x_unprocessed.log")
.SpecialSources
.LoggingErrorsAndWarningsCategory
.SendTo
.FlatFile("Error Listener")
.FormatWith(formatBuilder)
.ToFile(@"C:\Projects\PowerShell\codekick2\codekick2\error.log");


var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);

EnterpriseLibraryContainer.ConfigureContainer(_configurator, configSource);
}
}

public interface ILsmLogging
{
void Log(string text, string category = "General", int eventId = 3000, int priority = 1, TraceEventType type = TraceEventType.Verbose, string title = "LSM Log Entry");
}
}


Das Ergebnis sieht etwas merkwürdig aus:

----------------------------------------
Timestamp: 02.06.2012 04:25:01&#xA;Message: Hallo&#xA;Category: General&#xA;Priority: 1&#xA;Event ID: 3000&#xA;Severity: Verbose&#xA;
----------------------------------------
----------------------------------------
Timestamp: 02.06.2012 04:25:01&#xA;Message: Log2&#xA;Category: General&#xA;Priority: 1&#xA;Event ID: 3000&#xA;Severity: Verbose&#xA;
----------------------------------------
----------------------------------------
Timestamp: 02.06.2012 04:26:08&#xA;Message: Hallo&#xA;Category: General&#xA;Priority: 1&#xA;Event ID: 3000&#xA;Severity: Verbose&#xA;
----------------------------------------
----------------------------------------
Timestamp: 02.06.2012 04:26:12&#xA;Message: Log2&#xA;Category: General&#xA;Priority: 1&#xA;Event ID: 3000&#xA;Severity: Verbose&#xA;
----------------------------------------

Vielleicht überarbeitest Du nochmal den Formatter :-)

LG, Michael
02.06.2012
mblaess 1,2k 1 9
mblaess 1,2k 1 9
Danke für die Antwort, funktioniert wie erwartet. Was ich allerdings noch nicht ganz verstanden habe, warum muss man den Container konfigurieren, wenn ich die Konfiguration in der App.config stehen habe, brauche ich die Containerkonfiguration ja auch nicht?
multi1209 04.06.2012

Stelle deine .net-Frage jetzt!
TOP TECHNOLOGIES CONSULTING GmbH