我该如何处理:
当前代码看起来像;
class Class1 : ISomeInterface
IFooService _service;
void SomeMethod(){
_service = new FooService(this);
.....
}
class FooService : IFooService
public FooService(ISomeInterface class1Implementer)
{
_class1Implementer = class1Implementer
}
我想用Autofac将FooService注入Class1。这个注册是如何完成的? 感谢名单。
答案 0 :(得分:2)
由于Class1
向'IFooService`提供数据(对自身的引用),因此必须引入接受这些数据的a factory delegate。请考虑以下代码:
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>
代表工作。