Spring.Net 简单实例-01(IOC)

本文介绍如何在Windows窗体应用程序中利用Spring.NET框架创建并配置IoC容器。通过定义接口和服务类,并配置App.config文件,实现了依赖注入。文章还提供了测试按钮的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.话不多说看操作.新建"Windows窗体应用程序"

2:通过配置文件创建IOC容器

  首先引入安装包

3:定义一个接口(更好的体现封装性,当然也可以直接使用类)

  定义一个类,实现接口

 

 4:配置App.config文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <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>
    <context>
      <resource uri="config://spring/objects"/>
    </context>
    <objects xmlns="http://www.springframework.net">
      <description>An  example that demonstrates simple IoC features.</description>
      <!--//type属性值必须是包含程序集名称在内的类型全名    "命名空间,程序集"-->
      <object name="UserInfoService"  type="YK.OA.SpringNet.UserInfoService, YK.OA.SpringNet">
        
        </object>
    </objects>
  </spring>
</configuration>
App.config

 5:添加测试按钮

using Spring.Context;
using Spring.Context.Support;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YK.OA.SpringNet
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IApplicationContext ctx = ContextRegistry.GetContext();
            //GetObject获得app配置文件的objext项=>创建实例
            IUserInfoService lister = (IUserInfoService)ctx.GetObject("UserInfoService");
            MessageBox.Show(lister.ShowMsg());
        }
    }
}
按钮代码(注意命名空间)

6:运行

 

转载于:https://www.cnblogs.com/YK2012/p/6597024.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值