昨天说了一下Castle与Autofac如何在MVC中的使用,今天再来简单说一下Spring.Net框架在MVC中如何依赖注入的。
官网:http://www.springframework.net/
项目结构图:
首先,我们要在项目中添加Spring.Net的类库引用,我们可以在Nuget中进行下载:
第二步,在web.config中配置,配置代码如下:
<!--spring.net配置--> <configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc5" /> </sectionGroup> </configSections> <spring> <context> <resource uri="file://~/Config/Controller.xml" /> <resource uri="file://~/Config/Service.xml" /> </context> </spring> <!--spring.net配置-->
第三步,新建Config文件夹,新建Controller.xml配置Controller中的依赖对象,新建Service.xml配置类库的注入对象。
Controller.xml代码:
<?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net"> <description>An example that demonstrates simple IoC features.</description> <!--object的name可以自定义,property中的属性name不能自定义--> <object name="base" type="SpringNetDemo.Controllers.PersonController,SpringNetDemo" singleton="false"> <property name="PersonService" ref="PersonService"></property> <property name="TestService" ref="TestService"></property> </object> <object name="test" type="SpringNetDemo.Controllers.TestController,SpringNetDemo" singleton="false"> <property name="PersonService" ref="PersonService"></property> </object> </objects>
Service.xml代码:
<?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net"> <object name="PersonService" type="SpringNetDemo.Service.PersonService, SpringNetDemo.Service" singleton="false" > </object> <object name="TestService" type="SpringNetDemo.Service.TestService, SpringNetDemo.Service" singleton="false" > </object> </objects>
第四步,新建类库SpringNetDemo.Service,并新建业务逻辑类PersonService,TestService及实体类Person代码如下:
PersonService.cs代码: public class PersonService { public string Msg(Person model) { return $"我的名字是:{model.Name},今年{model.Age}岁。"; } } TestService.cs代码: public class TestService { public string Msg(Person model) { return $"我叫:{model.Name},今年{model.Age}了。"; } } Person.cs实体类代码: public class Person { public string Name { get; set; } public int Age { get; set; } }
第五步,修改全局文件Global.asax中MvcApplication继承自SpringMvcApplication
第六步,新建PersonController,代码如下:
public class PersonController : BaseController { public PersonService PersonService { get; set; } public TestService TestService { get; set; } // GET: Person public ActionResult Index() { Person person = new Person() { Name = "张珊", Age = 69 }; var result = PersonService.Msg(person); return Content(result+"--------"+ TestService.Msg(person)); } }
运行结果如下: