首页 > 代码库 > Unity中使用多构造函数(转)
Unity中使用多构造函数(转)
如果要实例化的类只有一个构造函数, 则使用方法很简单使用方法如下:
1 2 3 4 5 6 7 | using (IUnityContainer container = new UnityContainer()) { UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection( "unity" ); section.Configure(container); //... ILogger logger = container.Resolve<ILogger>( "DatabaseLogger" ); return logger; } |
其中配置文件为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?xml version= "1.0" encoding= "utf-8" ?> <configuration> <configSections> <section name= "unity" type= "Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration" /> </configSections> <unity> <containers> <container> <types> <type type= "Bery.ILogger, UnityStudy" mapTo= "Bery.DatabaseLogger, UnityStudy" name= "DatabaseLogger" > </type> </types> </container> </containers> </unity> </configuration> |
如果DatabaseLogger类中的有两个构造函数, 代码如下
1 2 3 4 5 6 | public DatabaseLogger() { } public DatabaseLogger(string name) { } |
则Unity自动使用参数最多的构造函数进行创建对象, 会抛出以下异常:
1 2 3 | Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "Bery.ILogger" , name = "DatabaseLogger" . Exception occurred while : while resolving. Exception is: InvalidOperationException - The type String cannot be constructed. You must configure the container to supply this value. |
如果您想让它使用无参的构造函数创建, 则要使用[InjectionConstructor]特性进行修饰无参的构造函数,
1 2 3 4 | [InjectionConstructor] public DatabaseLogger() { } |
若您想使用带参数的构造函数创建对象, 除了在构造函数上使用[InjectionConstructor]外, 还要在创建时传递参数,代码如下
1 2 3 4 5 6 7 8 9 10 | using (IUnityContainer container = new UnityContainer()) { UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection( "unity" ); section.Configure(container); ILogger logger = container.Resolve<ILogger>( "DatabaseLogger" , new ParameterOverrides{ { "name" , "logName" } }); return logger; |
引用地址:http://unity3d.9tech.cn/news/2014/0208/39766.html
Unity中使用多构造函数(转)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。