由于Class1
向“IFooService”提供数据(对自身的引用),因此您必须引入一个接受这些数据的工厂委托。考虑以下代码:
class Class1 : ISomeInterface
{
private readonly IFooService _service;
public Class1(Func<ISomeInterface, IFooService> fooServiceFactory)
{
_service = fooServiceFactory(this);
.....
}
}
现在,注册过程如下:
var builder = new ContainerBuilder();
builder.RegisterType<Class1>().As<ISomeInterface>();
builder.RegisterType<FooService>().As<IFooService>();
var container = builder.Build();
var something = container.Resolve<ISomeInterface>();
Autofac 将自动解析Func<..>
类型以匹配IFooService
类型和ISomeInterface
构造函数参数。
更新:与评论中正在进行的讨论有关。SomeMethod
与实现脱钩ISomeInterface
:
// Class1 is now oblivious to IFooService
class Class1 : ISomeInterface
{
public Class1()
{
}
}
// Class2 now holds the SomeMethod logic
class Class2 : ISomeOtherInterface
{
private readonly IFooService _fooService;
public Class2(IFooService fooService)
{
_fooService = fooService;
}
public void SomeMethod()
{
// do something with _fooService
}
}
如果SomeMethod
不能分开Class1
我还是会去工厂替代。这是一个轻微的修改,但IFooService
直到实际需要时才会解决,也SomeMethod
就是调用时。
class Class1 : ISomeInterface
{
private readonly Func<ISomeInterface, IFooService> _fooServiceFactory;
public Class1(Func<ISomeInterface, IFooService> fooServiceFactory)
{
_fooServiceFactory = fooServiceFactory;
}
void SomeMethod()
{
var fooService = _fooServiceFactory(this);
....
}
}
Autofac 工厂功能再次大放异彩。无需额外注册即可让Func<ISomeInterface, IFooService>
代表工作。