且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ninject 缓存注入的 DataContext?生命周期管理?

更新时间:2023-01-25 17:38:10

对于任何生命周期必须显式管理的对象(例如实现 IDisposable 的对象)或对用户很重要的对象,尽量不要注入它们,而是注入一个允许创建此类对象的工厂.例如定义这个接口:

For any object which lifetime must explicitly managed (such as objects that implement IDisposable) or matters to the user, try not to inject them, but inject a factory that allows creating such objects instead. Define this interface for instance:

public interface IDbDataContextFactory
{
    dbDataContext CreateNew();
}

并按如下方式使用它:

public class SqlPupilBlockService
{
    private IDbDataContextFactory contextFactory;

    public SqlPupilBlockService(
        IDbDataContextFactory contextFactory)
    {
        this.contextFactory = contextFactory;
    }

    public void DoSomeOperation()
    {
        using (var db = this.contextFactory.CreateNew())
        {
           // use the dbDataContext here.
        }
    }
}

的实现将非常简单,如下所示:

An implementation of would be very simple, like this:

public class DbDataContextFactory : IDbDataContextFactory
{
    public dbDataContext CreateNew()
    {
        return new dbDataContext();
    }
}

注册是这样的:

Bind<IDbDataContextFactory>().To<DbDataContextFactory>();

工厂的使用使得谁是所创建对象的所有者以及谁应该控制其生命周期变得非常明确.这使您的代码更具可读性,并遵循最小惊喜原则.

The use of a factory makes it very explicit who is the owner of the created object and who should control its lifetime. This makes your code more readable and follows the principle of least surprise.

更新

自从我提交这个答案已经一年多了.我现在不使用工厂,而是经常注入数据上下文本身,并在每个(Web)请求的基础上注册它.然而;可能需要改变设计应用程序的方式,一如既往:这取决于.请查看这个答案.

More than a year has past since I submitted this answer. Instead of using factories, I now often inject the data context itself, and register it on a per (web) request basis. However; a shift in how you need to design your application might be needed, so as always: it depends. Please take a look at this answer.