开发者

Autofac - Service constructor takes reference to instantiating object

How do I deal with:

Current code looks like;

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

class FooService : IFooS开发者_StackOverflow社区ervice
    public FooService(ISomeInterface class1Implementer)
    {
        _class1Implementer = class1Implementer
    }

I want to inject the FooService into Class1 with Autofac. How is this registration done? Thanx.


Since Class1 provides data (a reference to itself) to the 'IFooService` you have to introduce a factory delegate that accepts those data. Consider the following code:

class Class1 : ISomeInterface
{
    private readonly IFooService _service;
    public Class1(Func<ISomeInterface, IFooService> fooServiceFactory)
    {
        _service = fooServiceFactory(this);
        .....
    }
}

Now, the registration goes simply like 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 will automagically resolve the Func<..> type to match the IFooService type and the ISomeInterface constructor parameter.

Update: related to the ongoing discussion in comments. Decoupling SomeMethod from the ISomeInterface implementation:

// 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
    }
}

If SomeMethod cannot be separated from Class1 I would still go for the factory alternative. Here is a slight modification though that results in IFooService will not be resolved until actually needed, that is when SomeMethod is called.

class Class1 : ISomeInterface
{
    private readonly Func<ISomeInterface, IFooService> _fooServiceFactory;
    public Class1(Func<ISomeInterface, IFooService> fooServiceFactory)
    {
        _fooServiceFactory = fooServiceFactory;
    }

    void SomeMethod()
    {
        var fooService = _fooServiceFactory(this);
        ....
    }
}

Again Autofac factory features shine. No additional registrations are necessary to get the Func<ISomeInterface, IFooService> delegate working.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜