C# 关于引用 IOC控制反转 依赖注入 Spring.Net
main 主函数体:
#region 这是传统的依赖没有反转
IUserInfoDal userinfodal = new UserInfoDal();
userinfodal.Show();
#endregion
//企业内部管理系统适合使用Spring.Net,这种模式不适合Web系统
#region 使用容器来创建一个实例(控制反转)
//安装spring.core包,初始化容器
IApplicationContext ctx = ContextRegistry.GetContext();
IUserInfoDal dal = ctx.GetObject("UserInfoDal") as IUserInfoDal;
dal.Show();
UserInfoService userInfoService = ctx.GetObject("UserInfoService") as UserInfoService;
userInfoService.Show();
#endregion
Console.ReadKey();
类与接口:
public interface IUserInfoDal
{
string Name { get; set; }
void Show();
}
public class UserInfoDal : IUserInfoDal
{
public string Name { get; set; }
public void Show()
{
Console.WriteLine("这是一个IOC容器测试 " + Name);
}
}
public class EFUserInfoDal : IUserInfoDal
{
public string Name { get; set; }
public void Show()
{
Console.WriteLine("EFUserInfoDal");
}
}
public class UserInfoService
{
public IUserInfoDal UserInfoDal { get; set; }
public void Show()
{
UserInfoDal.Show();
Console.WriteLine("UserInfoService ");
}
}
配置文档:
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
</sectionGroup>
</configSections>
<spring>
<!--Spring.Net对象容器的配置-->
<context>
<!--容器里面的所有的对象在哪里配置的?-->
<resource uri="config://spring/objects"/>
</context>
<!--objects:配置的容器的里面的对象的-->
<objects xmlns="http://www.springframework.net">
<!--<description>An example that demonstrates simple Ioc features.</description>-->
<!--简单属性注入-->
<object name="UserInfoDal" type="ConsoleApp.UserInfoDal,ConsoleApp">
<property name="Name" value="牛气冲天"/>
</object>
<!--复杂属性注入-->
<object name="UserInfoService" type="ConsoleApp.UserInfoService,ConsoleApp">
<property name="UserInfoDal" ref="UserInfoDal"/>
</object>
</objects>
</spring>