【问题标题】:Lost scope using DependencyResolver in another class library, using Castle Windsor and FluentNhibernate and NHibernate在另一个类库中使用 DependencyResolver 丢失范围,使用 Castle Windsor 和 FluentNhibernate 和 NHibernate
【发布时间】:2015-04-19 06:38:18
【问题描述】:

在我的 WCF 项目中,我在 global.asax 中使用 Castle Windsor 注册了我的界面:

            Component.For<IStrategy>()
                .ImplementedBy<MyStrategy>()
                .LifestylePerWcfOperation(),

然后在同一个文件中,我使用 FluentNhibernate 使用提供程序配置 NHibernate:

FluentConfiguration configuration = Fluently.Configure()
            .Database(
                MsSqlConfiguration.MsSql2008.ConnectionString(myConnString)
                .Provider<ConnectionProvider>())
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<TenantMap>()) etc etc

但是,此 ConnectionProvider 托管在一个公共共享 dll 库中,因为还有其他 WCF 服务需要使用它。我想按如下方式注册此依赖项,但它不起作用,这意味着我必须手动新建一个实例。

    public ConnectionProvider()
    {    
        // doesnt work
        using (IDependencyScope scope = GlobalConfiguration.Configuration.DependencyResolver.BeginScope())
        {
            _myStrategy = scope.GetService<IStrategy>();
        }
    }

有没有办法让这个工作?它就像它现在在另一个组件中一样失去了范围。在同一个程序集中,DependencyScope 工作正常并创建了一个实例,但我想将它保存在一个共享的 dll 中。

编辑:我得到的错误是“System.Web.Http.Dependencies.EmptyResolver”在这段代码的手表上:GlobalConfiguration.Configuration.DependencyResolver

【问题讨论】:

    标签: nhibernate dependency-injection fluent-nhibernate castle-windsor dependency-resolver


    【解决方案1】:

    我可以看到上面的代码有几个问题:

    1) 您正在使用每个 WcfOperation 生活方式注册 IStrategy,MyStrategy。这意味着 windsor 将为每个 WcfOperation 创建一个策略。另一方面,您正在尝试使用 scope.GetService 手动设置组件的生活方式。要使 scope.GetService 发挥作用,您需要一种生活方式。

    2) 假设上面 ConnectionProvider 的代码是构造函数,那么构造函数似乎试图从容器中获取一些东西。这通常是个坏主意,在使用像 windsor 这样的 Ioc 容器时更糟。而是将 IStrategy 传递给构造函数(注入它)。

    3) 看到你这里调用容器是构造函数,大概说明你没有遵循容器调用3次,注册组件1次,获取顶层组件1次的原则,和 1 释放容器。

    我建议您阅读更多有关依赖注入和 Ioc 容器的信息,以全面了解如何使用此容器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-27
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多