简单的Injector参数附加到Factory

时间:2016-12-13 19:31:01

标签: c# asp.net dependency-injection inversion-of-control

为简洁起见,我将使用一些简短的通用命名约定。如果我有:

public class Factory : IFactory
{
     private readonly string dbConnection;
     public Factory(string dbConnection)
     {
          this.dbConnection= dbConnection;
     }

     public IDataContext Create() => new DataContext(dbConnection);
}

Factory类有一个字段,由构造函数设置。 Simple Injector如何支持传递该参数?如果你实施:

public class Service
{
     private IFactory Factory { get; }
     public Service(IFactory factory)
     {
         Factory = factory;
     }

     public void Save()
     {
          using(var context = Factory.Create())
              context.Insert(...);
     }
}

在初始化或实例化时,参数永远不会传递给Factory或通过ContainerFactory.Register<IFactory, Factory>(Lifestyle.Transient); 。注册依赖项时,它看起来不可能:

IEventHandler

我正在查看{{1}}接口,它是Simple Injector的一部分,看起来它会解决这个问题,但是你应该如何在这个实例中传递一个参数?

1 个答案:

答案 0 :(得分:0)

container.RegisterSingleton<IFactory>(new Factory("constr"));