1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Asp.net MVC中如何实现依赖注入(DI)(二)

Asp.net MVC中如何实现依赖注入(DI)(二)

时间:2019-12-30 17:12:45

相关推荐

Asp.net MVC中如何实现依赖注入(DI)(二)

昨天说了一下Castle与Autofac如何在MVC中的使用,今天再来简单说一下框架在MVC中如何依赖注入的。

官网:/

项目结构图:

首先,我们要在项目中添加的类库引用,我们可以在Nuget中进行下载:

第二步,在web.config中配置,配置代码如下:

<!--配置--><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><!--配置-->

View Code

第三步,新建Config文件夹,新建Controller.xml配置Controller中的依赖对象,新建Service.xml配置类库的注入对象。

Controller.xml代码:

<?xml version="1.0" encoding="utf-8" ?><objects xmlns=""><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>

View Code

Service.xml代码:

<?xml version="1.0" encoding="utf-8" ?><objects xmlns=""><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>

View Code

第四步,新建类库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; }}

View Code

第五步,修改全局文件Global.asax中MvcApplication继承自SpringMvcApplication

第六步,新建PersonController,代码如下:

public class PersonController : BaseController{public PersonService PersonService { get; set; }public TestService TestService { get; set; }// GET: Personpublic ActionResult Index(){Person person = new Person(){Name = "张珊",Age = 69};var result = PersonService.Msg(person);return Content(result+"--------"+ TestService.Msg(person));}}

View Code

运行结果如下:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。