Unity中使用多構造函數

若是要實例化的類只有一個構造函數, 則使用方法很簡單使用方法以下:ide

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類中的有兩個構造函數, 代碼以下this

1
2
3
4
5
6
public DatabaseLogger()
}
public DatabaseLogger(string name)
{
}

則Unity自動使用參數最多的構造函數進行建立對象, 會拋出如下異常:spa

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]特性進行修飾無參的構造函數,code

1
2
3
4
[InjectionConstructor]
public DatabaseLogger()
}

若您想使用帶參數的構造函數建立對象, 除了在構造函數上使用[InjectionConstructor]外, 還要在建立時傳遞參數,代碼以下xml

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;
相關文章
相關標籤/搜索