C# 关于引用 IOC控制反转 依赖注入 Spring.Net

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>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值