使用应由DI容器解决的依赖关系来实现被动属性 [英] Implementing passive attributes with dependencies that should be resolved by a DI container

查看:210
本文介绍了使用应由DI容器解决的依赖关系来实现被动属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在ASP中实施被动属性 .NET Web API。我实现的过滤器对存储库有依赖关系,它本身具有对自定义DbContext的依赖。
在这篇文章中,它表示您可以使用DI容器来解析组件,但也可以从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.

不知道很多关于你的代码,你应该可以使用抽象工厂定义一个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,而实际的Repository将以瞬态方式创建。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆