简单注入器 - 将构造函数参数传递给容器

Simple Injector - passing constructor argument to container

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

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

如何使用 Simple Injector 完成此操作?我有 HibernateFactory class,其中绑定是与存储库完成的:

        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 class 具有以下内容:

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)选项,如果有,如何?

不支持将运行时值传递给 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<IRepository<SomeEntity>>() 或使用 IRepository<T> 作为构造函数参数解析存储库。