jsD*_*via 7 c# asp.net-mvc dependency-injection unity-container serilog
我发现了serilog(.net的结构化日志),并发现了很多优点.但是我遇到了一些问题.我有4个项目,一个是web,一个是基础设施,另外两个是windows服务,我想声明一次serilog配置并多次使用它.而且我也希望将它与依赖注入一起使用.我已经在网上搜索了三天了,但我没有找到任何有用的东西,请一些人帮助我.
例如,我希望这个类成为我的日志类.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我不知道应该把这行代码放在哪里:
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
Tnx提前.
首先,在您的 Unity 配置中,要正确解析 Serilog,您需要使用 InjectionFactory,如下所示:
container.RegisterType<ILogger>(new ContainerControlledLifetimeManager(), new InjectionFactory((ctr, type, name) =>
{
ILogger log = new LoggerConfiguration()
.WriteTo.Console() //Your serilog config here
.CreateLogger();
return log;
}));
Run Code Online (Sandbox Code Playgroud)
在我的实现中,我没有抽象 Serilog,但无论如何上面的代码都是缺失的链接。IMyLogger 只需要参数注入 ILogger,一切都会自己解决。
这解决了 MVC 部分:您可以将 IMyLogger 注入 MVC 中的控制器。
这使我们可以在您的解决方案中找到它。由于您对服务的需求,您可能需要有一个单独的控制反转项目 (MySolution.InversionOfControl),其中包含您的绑定。然后,例如在您网站的 UnityWebActivator.cs 中,您可以执行以下操作:
/// <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));
}
Run Code Online (Sandbox Code Playgroud)
为您的服务做同样的事情,您应该一切顺利!
| 归档时间: |
|
| 查看次数: |
3757 次 |
| 最近记录: |