代码之家  ›  专栏  ›  技术社区  ›  Dmitry S.

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

  •  2
  • Dmitry S.  · 技术社区  · 13 年前

    假设我有以下课程。

    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容器,使其始终将具有特定基元类型和名称的参数解析为不同类中的特定值?

    我知道你可以为每种类型注册注入构造函数,这对我来说似乎很脆弱。另一种方法可能是将字符串参数封装在自定义类中。但我想知道是否有一种方法可以处理特定的基元类型构造函数参数。

    2 回复  |  直到 13 年前
        1
  •  2
  •   Community Mohan Dere    9 年前

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

    IApp设置

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

    单位配置

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

    服务1

    public class Service1
    {
        public Service1(Dependency1 dependency1, Dependency2 dependency2, IAppSettings appSettings)
        {
            var mySetting = appSettings.MySetting;
        }
    }
    

    以下是基本参数的一些选项: Register a type with primitive-arguments constructor?

        2
  •  0
  •   Peter Ritchie    13 年前

    我认为你无法让Unity下定决心 全部的 string 任何类的名为“myAppSettings”的参数。但是,您可以让它按名称解析特定类的参数。类似于:

    Container.RegisterType<Service2, Service2>(
                new InjectionConstructor(
                        new ResolvedParameter<string>(), 
                            "myAppSetting"));