Flo*_*iwi 3 c# generics unity-container
我正在尝试熟悉asp.net mvc,目前正在设置日志记录。
我看了一下Microsoft.Extensions.Logging并阅读了有关如何设置它的信息,但我一直在努力统一类型注册。
我想为
public HomeController(ILogger<HomeController> logger)
Run Code Online (Sandbox Code Playgroud)
我可以这样
private static void RegisterLoggingTypes(IUnityContainer container)
{
ILoggerFactory loggerFactory = new LoggerFactory()
.AddConsole()
.AddDebug();
container.RegisterType<ILogger<HomeController>>(new InjectionFactory(c => loggerFactory.CreateLogger<HomeController>()));
}
Run Code Online (Sandbox Code Playgroud)
但是我不想为每种类型都声明一个。我试过了
container.RegisterType(typeof(ILogger<>), new InjectionFactory((c,t,s) => loggerFactory.CreateLogger(t)));
Run Code Online (Sandbox Code Playgroud)
但这返回的ILogger是一个ILogger(of HomeController)
知道我该怎么做吗?
谢谢
我已经弄清楚了。我需要使用反射来生成通用方法,然后调用该方法。
var factoryMethod = typeof(LoggerFactoryExtensions).
GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).
First(x => x.ContainsGenericParameters);
container.RegisterType(typeof(ILogger<>), new InjectionFactory((c, t, s) =>
{
var genFactoryMethod = factoryMethod.MakeGenericMethod(t.GetGenericArguments()[0]);
return genFactoryMethod.Invoke(null, new object[] { loggerFactory });
}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
543 次 |
| 最近记录: |