C# Ioc容器Unity,简单实用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C# Ioc容器Unity,简单实用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1994字,纯文字阅读大概需要3分钟。
内容图文
原文:C# Ioc容器Unity,简单实用
开头先吐槽一下博客园超级不好用,添加图片后就写不动字了,难道是bug
好进入正题,先来说下依赖注入,简单来说就是定义好接口,上层代码调用接口,具体实现通过配置文件方式去指定具体实现类。
首先我们需要通过nuget来安装unity
安装好后就可以写一个方法类去实现依赖注入
public class UnityIocHelper : IServiceProvider { private readonly IUnityContainer _container; private static readonly UnityIocHelper dbinstance = new UnityIocHelper("DBcontainer"); private UnityIocHelper(string containerName) { UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); _container = new UnityContainer(); section.Configure(_container, containerName); } public static UnityIocHelper DBInstance { get { return dbinstance; } } public object GetService(Type serviceType) { return _container.Resolve(serviceType); } public T GetService<T>() { return _container.Resolve<T>(); } public T GetService<T>(params ParameterOverride[] obj) { return _container.Resolve<T>(obj); } public T GetService<T>(string name, params ParameterOverride[] obj) { return _container.Resolve<T>(name, obj); } }
具体调用方法
public static IDatabase Base(string connString) { return UnityIocHelper.DBInstance.GetService<IDatabase>(“MySql”, new ParameterOverride( "connString", connString)); }
配置信息
<unity> <typeAliases> <typeAlias alias="IDatabase" type="LRMC.Data.IDatabase,LRMC.Data" /> <typeAlias alias="SqlServer" type="LRMC.Data.SqlDapper.Database,LRMC.Data.SqlDapper" /> <typeAlias alias="MySql" type="LRMC.Data.MySqlDapper.Database,LRMC.Data.MySqlDapper" /> </typeAliases> <containers> <container name="DBcontainer"> <!-- 默认数据库软件类型:SqlServer,MySql,Oracle,Access,SQLite--> <type type="IDatabase" mapTo="SqlServer" name="SqlServer"></type > <type type="IDatabase" mapTo="MySql" name="MySql"></type > </container> </containers> </unity>
typeAlias 指定一个类的别名,
<type type="IDatabase" mapTo="MySql" name="MySql"></type >就是
IDatabase这个接口通过
MySql(
LRMC.Data.MySqlDapper.Database
)这个类去实现。
内容总结
以上是互联网集市为您收集整理的C# Ioc容器Unity,简单实用全部内容,希望文章能够帮你解决C# Ioc容器Unity,简单实用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。