C# 通过多个控制器共享数据。ASP.NETMVC

C# 通过多个控制器共享数据。ASP.NETMVC,c#,asp.net-mvc,controller,repository,ninject,C#,Asp.net Mvc,Controller,Repository,Ninject,如果我有两个控制器: public class PrimaryController : Controller { private IRepository<Primaries> repository; public PrimaryController(IRepository<Primaries> repository) { this.repository = repository; } // CRUD operat

如果我有两个控制器:

public class PrimaryController : Controller
{
    private IRepository<Primaries> repository;

    public PrimaryController(IRepository<Primaries> repository)
    {
        this.repository = repository;
    }

    // CRUD operations
}
这能正常工作吗?我的意思是,控制器会使用相同的存储库实例吗


谢谢

简单的答案-是!代码将对所有控制器使用相同的实现,除非您使用When…方法明确配置其他控制器

如果您不希望重用实现,而是希望重用对象的同一实例,那么可以像对ISession和ISessionFactory所做的那样,使用诸如
InScope
InRequestScope
InSingletonScope
之类的方法对其进行配置

从文件:

// Summary:
//     Indicates that instances activated via the binding should be re-used within
//     the same HTTP request.
IBindingNamedWithOrOnSyntax<T> InRequestScope();


//
// Summary:
//     Indicates that only a single instance of the binding should be created, and
//     then should be re-used for all subsequent requests.
IBindingNamedWithOrOnSyntax<T> InSingletonScope();
//摘要:
//指示通过绑定激活的实例应在中重新使用
//相同的HTTP请求。
IBindingNamedWithOrOnSyntax在RequestScope()中;
//
//总结:
//指示只应创建绑定的单个实例,以及
//然后应重新用于所有后续请求。
IBindingNamedWithOrOnSyntax InSingletonScope();

在singleton中使用
Repository
不是一个好主意。我在RequestScope中使用
使一个实例只服务一个请求。如果使用实体框架,您可以查看详细信息

这取决于ninject中默认范围的工作方式(我不是ninject用户)

但是,如果您在存储库映射中指定
InRequestScope
,它将起作用

this.Bind(typeof(IRepository<>))
    .To(typeof(Repository<>))
    .InRequestScope();
this.Bind(typeof(IRepository))
.To(类型(存储库))
.InRequestScope();
只要与数据库的连接没有关闭,单例作用域就可以工作。当应用程序停止工作时,它将停止工作,因为所有请求仍将尝试使用相同的存储库对象

这就是为什么请求范围更好。如果repos失败,它只会在一个请求中失败(除非db有问题)


我已经编写了一套最佳实践:

是的,我需要相同的实例。那么我应该在SingletonScope中使用
吗?
// Summary:
//     Indicates that instances activated via the binding should be re-used within
//     the same HTTP request.
IBindingNamedWithOrOnSyntax<T> InRequestScope();


//
// Summary:
//     Indicates that only a single instance of the binding should be created, and
//     then should be re-used for all subsequent requests.
IBindingNamedWithOrOnSyntax<T> InSingletonScope();
this.Bind(typeof(IRepository<>))
    .To(typeof(Repository<>))
    .InRequestScope();