【问题标题】:Sharing data thru several controllers. ASP.NET MVC通过多个控制器共享数据。 ASP.NET MVC
【发布时间】:2012-03-14 06:28:53
【问题描述】:

如果我有两个控制器:

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

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

    // CRUD operations
}

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

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

    // CRUD operations
    public ActionResult CreateSomethingAuxiliary(Guid id, AuxiliaryThing auxiliary)
    {
        var a = repository.Get(id);
        a.Auxiliaries.Add(auxiliary);
        repository.Save(a);

        return RedirectToAction("Details", "Primary", new { id = id });
    }
}

DI 的实现方式类似(代码来自Ninject 模块)

this.Bind<ISessionFactory>()
    .ToMethod(c => new Configuration().Configure().BuildSessionFactory())
    .InSingletonScope();

this.Bind<ISession>()
    .ToMethod(ctx => ctx.Kernel.TryGet<ISessionFactory>().OpenSession())
    .InRequestScope();

this.Bind(typeof(IRepository<>)).To(typeof(Repository<>));

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

谢谢!

【问题讨论】:

    标签: c# asp.net-mvc controller repository ninject


    【解决方案1】:

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

    如果您想重用不是实现,而是对象的相同实例,您可以使用 InScopeInRequestScopeInSingletonScope 等方法进行配置,就像您已经为 ISession 和 ISessionFactory 所做的那样.

    来自文档:

    // 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();
    

    在单例中使用Repository 不是一个好主意。我使用InRequestScope 让一个实例只服务一个请求。如果使用实体框架,您可以查看this answer了解详情

    【讨论】:

    • 是的,我需要相同的实例。那么我应该使用InSingletonScope吗?
    【解决方案2】:

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

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

    this.Bind(typeof(IRepository<>))
        .To(typeof(Repository<>))
        .InRequestScope();
    

    只要与数据库的连接没有关闭,单例​​范围就可以工作。您的应用程序将停止工作,因为所有请求仍会尝试使用相同的存储库对象。

    这就是请求范围更好的原因。如果 repos 失败,它只会失败一个请求(除非它是 db 的问题)。

    我写了一套最佳实践:http://blog.gauffin.org/2011/09/inversion-of-control-containers-best-practices/

    【讨论】:

      猜你喜欢
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 2017-07-16
      • 1970-01-01
      • 2014-03-17
      • 2011-08-21
      • 1970-01-01
      相关资源
      最近更新 更多