具有相关性,应该由一个DI容器来解决实现被动属性 [英] Implementing passive attributes with dependencies that should be resolved by a DI container
问题描述
我想实现被动属性在ASP.NET Web API 的。我采取的过滤器上的存储库,它本身有一个自定义的DbContext依赖的依赖。
在后它说,你可以解决一个DI容器的组成部分,也是该code应的Application_Start被调用。
我不知道如何实现这一点,而采取的DI容器的生命周期管理功能的优势(这样一个新的DbContext在每次请求使用)。将注入一个抽象工厂是一个很好的解决方案?还是有更简单的东西,我很想念。
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.
推荐答案
您可以通过滑动 Decoraptor解决此问题的在过滤器和存储库之间。
You can resolve this issue by sliding a Decoraptor in between the Filter and the Repository.
不知道很多关于你的code,你应该能够定义使用抽象工厂一个Decoraptorepository:
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...
}
这使您的过滤器,以保持一个Singleton,而处于过渡的方式正在创建的实际存储库。
This enables your Filter to stay a Singleton, while the actual Repository is being created in a Transient manner.
如果您需要处置的对象太多,请参考后续的文章如何取消从Decoraptor 内瞬时对象。
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.
这篇关于具有相关性,应该由一个DI容器来解决实现被动属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!