gpt4 book ai didi

asp.net-mvc - 依赖注入(inject)能走多远?

转载 作者:行者123 更新时间:2023-12-03 14:36:29 24 4
gpt4 key购买 nike

我的网络应用解决方案包含 3 个项目:

  • Web 应用 (ASP.NET MVC)
  • 业务逻辑层(类库)
  • 数据库层( Entity Framework )

  • 我想使用 Ninject 来管理 DataContext 的生命周期由 Entity Framework 生成在 Database Layer .

    业务逻辑层由引用存储库(位于数据库层)的类组成,我的 ASP.NET MVC 应用程序引用业务逻辑层的服务类来运行代码。每个存储库创建一个 MyDataContext 的实例。来自 Entity Framework 的对象

    存储库
    public class MyRepository
    {
    private MyDataContext db;
    public MyRepository
    {
    this.db = new MyDataContext();
    }

    // methods
    }

    业务逻辑类
    public class BizLogicClass
    {
    private MyRepository repos;
    public MyRepository
    {
    this.repos = new MyRepository();
    }

    // do stuff with the repos
    }

    Ninject 会处理 MyDataContext 的生命周期吗?尽管从 Web 应用程序到数据层的依赖链很长?

    最佳答案

    编辑

    前段时间我遇到了一些问题,但现在它似乎可以工作:

    Bind<CamelTrapEntities>().To<CamelTrapEntities>().Using<OnePerRequestBehavior>();

    您可以使用 OnePerRequestBehavior 而不是使用 HttpModule,它将负责处理当前请求中的上下文。

    编辑 2

    OnePerRequestBehavior 需要在 web.config 中注册,因为它也依赖于 HttpModule:

    在 IIS6 中:
    <system.web>
    <httpModules>
    <add name="OnePerRequestModule" type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/>
    </httpModules>
    </system.web>

    使用 IIS7:
    <system.webServer> 
    <modules>
    <add name="OnePerRequestModule" type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/>
    </modules>
    </system.webServer>

    上一个答案

    在不需要时处理上下文是您的责任。 ASP.NET 中最流行的方法是每个请求都有一个 ObjectContext。我通过使用 HttpModule 来做到这一点:
    public class CamelTrapEntitiesHttpModule : IHttpModule
    {
    public void Init(HttpApplication application)
    {
    application.BeginRequest += ApplicationBeginRequest;
    application.EndRequest += ApplicationEndRequest;
    }

    private void ApplicationEndRequest(object sender, EventArgs e)
    {
    ((CamelTrapEntities) HttpContext.Current.Items[@"CamelTrapEntities"]).Dispose();
    }

    private static void ApplicationBeginRequest(Object source, EventArgs e)
    {
    HttpContext.Current.Items[@"CamelTrapEntities"] = new CamelTrapEntities();
    }
    }

    这是注入(inject)规则:
    Bind<CamelTrapEntities>().ToMethod(c => (CamelTrapEntities) HttpContext.Current.Items[@"CamelTrapEntities"]);

    我的存储库在构造函数中使用 ObjectContext:
    public Repository(CamelTrapEntities ctx)
    {
    _ctx = ctx;
    }

    关于asp.net-mvc - 依赖注入(inject)能走多远?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2440790/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com