Unity依赖注入
1、在WestJob.Data.Factory空间里面添加一个接口
namespace WestJob.Data.Factory
{
public interface ItestA
{
string returnValue();
}
}
2、在WestJob.Data.SqlServerAccess空间里面添加一个类
namespace WestJob.Data.SqlServerAccess
{
public class testA : ItestA
{
public string returnValue()
{
return "it's ok!";
}
}
}
3、在web.config里面添加节点
3.1、先在configSections节点下声明一个testSection的节点
<configSections> <section name="testSection" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/> </configSections>
3.2、然后在下面定义这个节点的内容
<testSection> <typeAliases> <typeAlias alias="IApplicationContext" type="WestJob.Data.Factory.IApplicationContext, WestJob.Data.Factory"/> <typeAlias alias="SqlServerContext" type="WestJob.Data.SqlServerAccess.SqlServerContext, WestJob.Data.SqlServerAccess"/> </typeAliases> <containers> <container name="SqlServerContainer"> <types> <type type="IApplicationContext" mapTo="SqlServerContext"> </type> </types> </container> </containers> </testSection>
4、最后就可以开始使用了
IUnityContainer container = new UnityContainer();
UnityConfigurationSection unitConfig =
ConfigurationManager.GetSection("testSection") as UnityConfigurationSection;
unitConfig.Configure(container, "testContainer");
这样就可以顺利的引用了,但是我在使用的过程中老是报错
The type name or alias SqlServerContext could not be resolved. Please check your configuration file and verify this type name.
或者是
给定程序集名称或基本代码无效
我仔细核对webconfig里面的命名空间,发现都没问题。后来发现原来是依赖注入的时候类名都在webconfig里面指定的,在代码里面没有指定类名,编译的时候不会报错。但其实该引用的程序集都没有引用到。
再补上两行类名的代码开发环境就能识别到错误了
IUnityContainer container = new UnityContainer();
UnityConfigurationSection unitConfig =
ConfigurationManager.GetSection("testSection") as UnityConfigurationSection;
unitConfig.Configure(container, "testContainer");
ItestA aa = container.Resolve<testA>();
var value = aa.returnValue();
ItestA和testA这两个类型在程序集都没有引用,只要引用了对应的程序集就OK了。
浙公网安备 33010602011771号