Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing passive attributes with dependencies that should be resolved by a DI container

I'm trying to implement passive attributes in an ASP.NET Web API. The filter I'm implementing has a dependency on a repository, which itself has a dependency on a custom DbContext. In the post it says that you can resolve the component with a DI container, but also that the code should be invoked from Application_Start. I'm not sure how to implement this, while taking advantage of the DI container's lifetime management capabilities (so that a new DbContext will be used per request). Would injecting an abstract factory be a good solution for this? or is there something simpler that I'm missing.

like image 544
nirw Avatar asked Aug 21 '14 18:08

nirw


1 Answers

You can resolve this issue by sliding a Decoraptor in between the Filter and the Repository.

Not knowing a lot about your code, you should be able to define a Decoraptorepository using an Abstract Factory:

public class Decoraptorepository : IRepository
{
    private readonly IFactory<IRepository> factory;

    public Decoraptorepository(IFactory<IRepository> factory)
    {
        this.factory = factory;
    }

    // Just guessing IRepository's member(s) here...
    public void Save(Foo foo)
    {
        this.factory.Create().Save(foo);
    }

    // other members...
}

This enables your Filter to stay a Singleton, while the actual Repository is being created in a Transient manner.

If you need to dispose of objects too, please refer to the follow-up article on how to decommission Transient objects from within a Decoraptor.

like image 78
Mark Seemann Avatar answered Nov 14 '22 12:11

Mark Seemann