解决实例使用Unity多个构造 [英] Resolve instance with multiple constructors using unity

查看:419
本文介绍了解决实例使用Unity多个构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个使用类的团结其中类有两个构造与相同数量的参数的一个实例。

I'd like to create an instance of a class using unity where the class has two constructors with the same number of parameters.

下面是实例:

_unityContainer.Resolve<IGradeType>(new ParameterOverride("gradeTypeStringFromXmlFile", gradeTypeStringFromXmlFile));

和这里的构造函数:

    public GradeType( string gradeTypeStringFromXmlFile)
    {
        _gradeTypeStringFromXmlFile = gradeTypeStringFromXmlFile;
    }

    public GradeType(Enum.GradeType gradeType)
    {
        _gradeType = gradeType;
    }

如果我尝试这样做,我得到一个例外,说的类型GradeType长度为1无法消除歧义的多个构造

If I try to do this I get an exception saying The type GradeType has multiple constructors of length 1. Unable to disambiguate.

我可以设置属性[InjectionConstructor]在一个构造,使之与一个工作,但然后,我不能创建使用其他构造与团结的一个实例。

I can set the attribute [InjectionConstructor] over one constructor to make it work with one, but then I can't create an instance with unity using the other constructor.

时,它的一些办法有同等数量的参数多个构造并仍然使用统一创建实例?

Is it some way to have multiple constructors with equal number of parameters and still use unity to create the instances?

推荐答案

是的,它是可能的团结告诉它应该使用哪个构造函数,但你只能做到这一点,当你使用的 InjectionConstructor 。如果你想使用这两个构造函数,它甚至复杂的,因为你有你的名字注册和解析使用时的名字

Yes it's possible to tell Unity which constructor should it use, but you can only do this when you register your type with InjectionConstructor. If you want to use both constructor it's even complicated because you have to name your registrations and use that name when resolving.

样品建有统一版本2.1.505:

Sample built with Unity version 2.1.505:

var continer = new UnityContainer();

continer.RegisterType<IGradeType, GradeType>("stringConstructor", 
    new InjectionConstructor(typeof(string)));

continer.RegisterType<IGradeType, GradeType>("enumConstructor",
    new InjectionConstructor(typeof(EnumGradeType)));

IGradeType stringGradeType = continer.Resolve<IGradeType>("stringContructor" , 
    new DependencyOverride(typeof(string), "some string"));

IGradeType enumGradeType = continer.Resolve<IGradeType>("enumConstructor", 
    new DependencyOverride(typeof(EnumGradeType), EnumGradeType.Value));

这篇关于解决实例使用Unity多个构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆