【问题标题】:Simple Injector - passing constructor argument to container简单注入器 - 将构造函数参数传递给容器
【发布时间】:2015-09-22 18:51:10
【问题描述】:

我正在将我的应用程序从 Ninject 转换为 Simpler Injector。我正在尝试通过 getInstance() 将构造函数参数(在本例中为 NHibernate 会话)传递到容器中。在ninject中,这是通过使用以下方式完成的:

return _kernel.Get<IRepository<T>>(new ConstructorArgument("mysession", GetMySession()));

如何使用 Simple Injector 完成此任务?我有 HibernateFactory 类,其中与存储库完成绑定:

        public class NHSessionFactory : IMySessionFactory
        {
            private readonly ISessionFactory myNHSessionFactory;

            public NHSessionFactory(Assembly[] myMappings){

                this.myNHSessionFactory = InitNHibernate(myMappings);

                MyLocator.MyKernel.Bind(typeof(IRepository<>)).To(typeof(NHRepository<>));
            }

            public IMySession CreateSession()
            {
                return new NHSession(this.myNHSessionFactory.OpenSession());
            }
            ....

MyLocator 类有以下内容:

public class MyLocator
{
    private static StandardKernel kernel;
    private static ISessionFactory sessionFactory;

    static MyLocator()
    {
        this.kernel = new StandardKernel();
        this.kernel.Load(new DependencyInjector());
    }

    public static StandardKernel MyKernel
    {
        get
        {
            return this.kernel;
        }
    }

   public static ISession GetMySession()
    {
         ....
     return this.kernel.Get<ISession>();
}
.....

public static IRepository<T> GetRepository<T>() where T : MyEntity
{
    return this.kernel.Get<IRepository<T>>(new ConstructorArgument("mysession", GetMySession()));
}

请告诉我如何使用 Simple Injector 实现这一目标。我已经读过 Simple Injector 不允许通过检索方法(即 getInstance)传递运行时值的开箱即用支持。有哪些替代方案?注册(RegisterConditional)是否有选项,如果有,怎么做?

【问题讨论】:

    标签: nhibernate simple-injector


    【解决方案1】:

    没有开箱即用的支持将运行时值传递给GetInstance 方法以完成自动连接过程。这是因为它通常是次优设计的标志。有ways around this,但总的来说我建议不要这样做。

    在您的情况下,即使在您当前的设计中,似乎完全没有必要在对象构造期间将会话作为运行时值传递(即使使用 Ninject 也是如此)。如果您只是在容器中注册 ISession,您可以让 Simple Injector(或 Ninject)为您自动连接它,而无需将其作为运行时值传递。这甚至可能消除对 IMySessionFactory 抽象和实现的需要。

    您的代码可能开始如下所示:

    Assembly[] myMappings = ...
    ISessionFactory myNHSessionFactory = InitNHibernate(myMappings);
    
    container.Register<IMySession>(myNHSessionFactory.OpenSession, Lifestyle.Scoped);
    
    container.Register(typeof(IRepository<>), typeof(NHRepository<>));
    

    使用此配置,您现在可以使用 container.GetInstance&lt;IRepository&lt;SomeEntity&gt;&gt;() 解析存储库或使用 IRepository&lt;T&gt; 作为构造函数参数。

    【讨论】:

      猜你喜欢
      • 2012-11-24
      • 1970-01-01
      • 2017-01-02
      • 2015-01-28
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      相关资源
      最近更新 更多