.net 使用Unity解析各种类型中的特定构造函数参数

.net 使用Unity解析各种类型中的特定构造函数参数,.net,unity-container,.net,Unity Container,假设我有以下课程 public class Service1 { public Service1(Dependency1 dependency1, Dependency2 dependency2, string myAppSetting) { } } public class Service2 { public Service2(DependencyA dependency1, ..., DependencyD dependency4, string myAppSett

假设我有以下课程

public class Service1
{
   public Service1(Dependency1 dependency1, Dependency2 dependency2, string myAppSetting)
   {
   }
}

public class Service2
{
   public Service2(DependencyA dependency1, ..., DependencyD dependency4, string myAppSetting)
   {
   }
}
Unity容器用于通过依赖项注入填充构造函数参数;决不会直接调用container.Resolve(..)方法

上面的类有各种参数,但最后一个参数
string myAppSetting
始终相同。有没有办法将Unity容器配置为始终将具有特定基元类型和名称的参数解析为不同类中的特定值


我知道你可以为我认为脆弱的每一种类型注册注入构造函数。另一种方法可能是在自定义类中包装字符串参数。但是我想知道是否有一种方法可以处理特定的基元类型构造函数参数。

我认为您无法获得Unity来解析任何类的所有名为“myAppSettings”的
字符串
参数。但是,您可以让它按特定类的名称解析参数。比如:

Container.RegisterType<Service2, Service2>(
            new InjectionConstructor(
                    new ResolvedParameter<string>(), 
                        "myAppSetting"));
Container.RegisterType(
新注入构造函数(
新的ResolvedParameter(),
“myAppSetting”);

我制作了一个界面来包装我的
AppSettings
。这允许我将应用程序设置注入到我的类型中

IAppSettings

public interface IAppSettings {
    string MySetting { get; set; }
    ...
}
UnityConfig

container.RegisterInstance<IAppSettings>(AppSettings.Current);
container.RegisterType<IService1, Service1>();
container.RegisterType<IService2, Service2>();

这里有一些基本参数选项:

它是否更像“新注入构造函数(新解析参数(),解析参数(),解析参数(),解析参数(),解析参数(),“myAppSettingValue”);”?我的问题是,如果您添加或删除注入的依赖项,代码就会中断。听起来最好的解决方法是将所有基元参数包装到类/接口中。您最终需要解析这些基元。因此,您需要为参数列表提供某种类型的构建器类,以使Unity配置不那么脆弱——这是您需要的。
public class Service1
{
    public Service1(Dependency1 dependency1, Dependency2 dependency2, IAppSettings appSettings)
    {
        var mySetting = appSettings.MySetting;
    }
}