代码之家  ›  专栏  ›  技术社区  ›  stiank81

使用带有额外参数的Unity Resolve创建对象

  •  12
  • stiank81  · 技术社区  · 15 年前

    我用的是棱镜,它也是一个很好的统一IOC容器。我对这个概念还不太熟悉,所以还没弄清楚。我现在要做的是使用ioc容器创建一个对象,但也传递一个额外的参数。请允许我举例说明:

    我有一个接受命令对象的类。这是在IOC容器中注册的,因此它可以很好地处理:

    public class Person 
    {
        public Person(IApplicationCommands commands) { .. }
        ..
    }
    
    Person person = _container.Resolve<Person>();
    

    现在-我想传递另一个论点-例如,那个人的名字。但是,我仍然希望使用IOC容器来处理解析,从而从IOC容器中获取其他参数。但作为“自定义”参数传入名称。能做到吗?

    public class Person 
    {
        public Person(IApplicationCommands commands, string name) { .. }
        ..
    }
    
    string name = "John"; 
    Person person = _container.Resolve<Person>(name); // ....?? 
    

    这个例子似乎不起作用,但有没有办法让它起作用?或者,Unity IOC容器是否要求在调用Resolve之前在容器中注册所有参数?

    4 回复  |  直到 10 年前
        1
  •  9
  •   Community CDub    8 年前

    NotDan's answer


    IUnityContainer subContainer = _container.CreateChildContainer();
    
    //Don't do this... create a custom type other than string, like
    // MyConstructorParams or something like that... this gets the point across.
    subContainer.RegisterInstance<string>("John");
    Person person = subContainer.Resolve<Person>();
    

    public class Person
    {
         public Person(IApplicationCommands commands)
         { .. }
         public void Initialize(string name) { .. }
    
         ..
    }
    

    Person person = container.Resolve<Person>();
    person.Initialize("John");
    

        2
  •  18
  •   Community CDub    8 年前

    Can I pass constructor parameters to Unity's Resolve() method?

    container.Resolve<IFoo>(new ParameterOverrides<Foo> { { "name", "bar" }, { "address", 42 } });"
    
        3
  •  4
  •   Derek Greer    15 年前

    Person person = _personFactory.CreatePerson("bubba");
    

    var person = new Person("bubba", _domainService);
    

    public class Person
    {
        public void DoSomethingWith(SomeStrategy strategy)
        {
            strategy.DoSomething(this);
        }
     }
    

        4
  •  0
  •   Steven Robbins    15 年前