MVC Autofac构造函数注入

建立 空的 MVC4项目

首先引用 NuGet 里 autofac 和 autofac .integration. mvc

然后 建立Model

public class Person

{

public int Id { get; set; }

public string Name { get; set; }

public int Age { get; set; }

public string Address { get; set; }

}

 

public interface IPersonRepository

{

IEnumerable GetAll();

Person Get(int id);

Person Add(Person item);

bool Update(Person item);

bool Delete(int id);

}

 

public class PersonRepository : IPersonRepository

{

List person = new List();

public PersonRepository()

{

Add(new Person { Id = 1, Name = "joye.net1", Age = 18, Address = "中国上海" });

Add(new Person { Id = 2, Name = "joye.net2", Age = 18, Address = "中国上海" });

Add(new Person { Id = 3, Name = "joye.net3", Age = 18, Address = "中国上海" });

}

public IEnumerable GetAll()

{

return person;

}

public Person Get(int id)

{

return person.Find(p => p.Id == id);

}

public Person Add(Person item)

{

if (item == null) { throw new ArgumentNullException("item"); }

person.Add(item);

return item;

}

public bool Update(Person item)

{

if (item == null) { throw new ArgumentNullException("item"); }

int index = person.FindIndex(p => p.Id == item.Id);

if (index == -1)

{

return false;

}

person.RemoveAt(index);

person.Add(item); return true;

}

 

public bool Delete(int id)

{

person.RemoveAll(p => p.Id == id);

return true;

}

}

 

 

再新建 HomeController 与相应的 Index.cshtml 在HomeController 声明 属性及构造函数

public class HomeController : Controller

{

public IPersonRepository _personRepository { get; set; }

public HomeController(IPersonRepository personRepository)

{

_personRepository = personRepository;

}

 public ActionResult Index()

{

var item = _personRepository.Get(1);

return View();

}

}

 

最后在global.asax.cs 的Application_Start() 里实现注入

using Autofac;
using Autofac.Integration.Mvc;

public class MvcApplication : System.Web.HttpApplication

{

protected void Application_Start()

{

var builder = new ContainerBuilder();

builder.RegisterType<PersonRepository>().As<IPersonRepository>(); //注册接口服务 

builder.RegisterControllers(Assembly.GetExecutingAssembly());//构造函数注入

//builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();//属性注入

var container = builder.Build();//构建

System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//开始注入

 

WebApiConfig.Register(GlobalConfiguration.Configuration);

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

RouteConfig.RegisterRoutes(RouteTable.Routes);

BundleConfig.RegisterBundles(BundleTable.Bundles);

}

}

转载于:https://www.cnblogs.com/zhshlimi/p/5509441.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值