2

我该如何处理:

当前代码看起来像;

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

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

我想用 Autofac 将 FooService 注入 Class1。这个注册是怎么做的?谢谢。

4

1 回答 1

2

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

于 2010-10-14T08:47:24.193 回答