9

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.

nirw
  • 225
  • 2
  • 10

1 Answers1

10

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.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • Wow, took me some time to wrap my head around both posts. The thing that took me more time to realize is that if you use the DI container inside the factory like in your [older post](http://blog.ploeh.dk/2012/03/15/ImplementinganAbstractFactory/) the container will also dispose any disposable dependencies according to the defined lifestyle. In my case at the end of the request. – nirw Aug 27 '14 at 19:36