Autofac - 服务构造函数引用实例化对象

时间:2010-10-13 22:53:23

标签: .net inversion-of-control autofac

我该如何处理:

当前代码看起来像;

class Class1 : ISomeInterface
    IFooService _service;
    void SomeMethod(){
        _service = new FooService(this);
        .....
}

class FooService : IFooService
    public FooService(ISomeInterface class1Implementer)
    {
        _class1Implementer = class1Implementer
    }

我想用Autofac将FooService注入Class1。这个注册是如何完成的? 感谢名单。

1 个答案:

答案 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构造函数参数。

与评论中正在进行的讨论相关的

更新。将SomeMethodISomeInterface实施解耦:

// 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>代表工作。