我有一个ILogger
接口和一个ILogger<T>
,它是实际实现并继承自前者的接口。我在ILogger<T>
注册了Autofac
界面,但它运行正常,但我必须要求ILogger<T>
。有可能在以下情况下做到:
class MyService
{
public MyService(ILogger logger)...
}
logger
实际上是ILogger<MyService>
答案 0 :(得分:0)
首先注册:来自docs
builder.RegisterGeneric(typeof(NHibernateRepository<>))
.As(typeof(IRepository<>))
.InstancePerLifetimeScope();
所以你的代码
builder.RegisterGeneric(typeof(LoggerService<>))
.As(typeof(ILogger<>))
.InstancePerLifetimeScope();
这是我的工作样本:
using System;
using Autofac;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(LoggerService<>))
.As(typeof(ILogger<>))
.InstancePerLifetimeScope();
var container = builder.Build();
var obj = container.Resolve<ILogger<MyService>>();
var obj2 = container.Resolve<ILogger<OtherService>>();
Console.WriteLine(obj.Log());
Console.WriteLine(obj2.Log());
}
}
public interface ILogger<T>
{
string Log();
}
public class LoggerService<T> : ILogger<T>
{
public string Log()
{
return typeof(T).Name;
}
}
public class MyService
{
}
public class OtherService
{
}
输出:
Hello World
为MyService
OtherService