How to use Serilog with Unity?
recencely i discoverd serilog ( structured logging for .net ) and saw a lot of its advantages. but i face some problems with it . i have 4 projects, one is web, one is infrastructure and the other two are windows services, i want to declare serilog configuration once and use it multiple times. and also i want to use it with dependency injection. i have been searching web for three days now , but i did not find any thing usefull, please some one help me.
for example i want this class to be my logging class.
public interface IMyLogger
{
void Information(string message, object[] parameters);
}
public class MyLogger : IMyLogger
{
public MyLogger()
{
}
public void Information(string message, object[] parameters)
{
Log.Information("LogType : {LogType} - Operation : {Operation}", parameters);
}
}
public class UserClass
{
private readonly IMyLogger _myLogger;
public UserClass(IMyLogger myLogger)
{
_myLogger = myLogger;
}
}
now i dont know where i should put this line of code :
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
tnx in advance.
First off, in your Unity configuration, to get Serilog resolving properly, you need to use an InjectionFactory, like this:
container.RegisterType<ILogger>(new ContainerControlledLifetimeManager(), new InjectionFactory((ctr, type, name) =>
{
ILogger log = new LoggerConfiguration()
.WriteTo.Console() //Your serilog config here
.CreateLogger();
return log;
}));
In my implementation I'm not abstracting Serilog, but the code above is the missing link in any case. IMyLogger just needs to parameter inject ILogger, and everything will work itself out.
That solves the MVC part: you can inject IMyLogger into your controllers in MVC.
Which brings us to where to locate this in your solution. Because of your needs regarding services, you probably need to have a separate Inversion of Control project (MySolution.InversionOfControl) that contains your bindings. Then, for instance in your web site's UnityWebActivator.cs, you can do something like this:
/// <summary>Integrates Unity when the application starts.</summary>
public static void Start()
{
//This is the important part:
var container = UnityConfig.GetConfiguredContainer(); //This is a static class in the InversionOfControl project.
//This is generic:
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
Do the same for your services, and you should be good to go!
链接地址: http://www.djcxy.com/p/85490.html上一篇: ILogger.Log方法declaringType参数
下一篇: 如何使用Serilog和Unity?