unity-具有正常分辨率的混合参数覆盖

时间:2019-02-21 13:54:23

标签: c# .net dependency-injection unity-container

我该如何在构造函数中仅指定一个参数,同时将其余参数照常注入Unity?

例如

public MyContentStore(string contentPath, IFileSystem fileSystem)
{
}

我希望能够在运行时指定内容路径,但是要通过注册类型自动注入文件系统。我似乎无法将 ParameterOverride ResolvedParameter

1 个答案:

答案 0 :(得分:0)

  

我希望能够在运行时指定内容路径

我想这意味着在解决过程中。它应该开箱即用,您不需要混合任何东西。只需注册您的类型而无需任何其他操作,然后在解析过程中覆盖您想要的参数

IUnityContainer uc = new UnityContainer();   
uc.RegisterType<IFileSystem, FileSystem>();
uc.RegisterType<MyContentStore>(); 
var ms = uc.Resolve<MyContentStore>(new ParameterOverride("contentPath", "123"));

另一方面,如果您想在注册过程中指定参数,则将无法进行,因为您需要指定每个参数。