autofac for mvc
2021-05-30 13:01
标签:interface vat rgba builder result 获取 对象 color 静态方法 1.首先需要安装 Autofac 和Autofac.Integration.Mvc install-package Autofac -version5.2.0 install-package Autofac.Integration.Mvc -version 5.0.0 2.编写依赖注入和解析器类,并在该类中增加静态方法,实现注入和依赖解析,通过 System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 来把当前的依赖注入加入到mvc框架中。 说明: 3.为了使依赖解析器能够在系统启动时启动,需要在Global.asax.cs 中调用依赖解析器类中的静态方法进行初始化。 4. 控制器抽象,重建一个控制器基类,并在其中增加以来注入对象获取的方法,根据传入的接口类型自动匹配注入的依赖,从而得到该接口的实例。其他控制器通过继承该类而共享该类方法来获取依赖解析对象。 示例正代码: 1.仓储接口 using autofacdemo2.Models; 2.仓储实现 using autofacdemo2.Models; namespace autofacdemo2.Repository }; 3.依赖解析类 using Autofac; } 4.控制器 using autofacdemo2.Repository; // GET: Home 5.控制器基类 using System.Web.Mvc; namespace autofacdemo2.Controllers 6.控制器派生类 using autofacdemo2.Repository; autofac for mvc 标签:interface vat rgba builder result 获取 对象 color 静态方法 原文地址:https://www.cnblogs.com/sundh1981/p/14672788.html
using System.Collections.Generic;
namespace autofacdemo2.Repository
{
public interface IStudentRepository
{
List
}
}
using System.Collections.Generic;
{
public class StudentRepository : IStudentRepository
{
private List
public StudentRepository()
{
students = new List
new Student{ Id=1,Name="张三",Sex="男",Grade="二(一)班" },
new Student{ Id=2,Name="李四",Sex="女",Grade="二(二)班" },
new Student{ Id=3,Name="王五",Sex="男",Grade="二(一)班" }
}
public List
{
return students;
}
}
}
using Autofac.Integration.Mvc;
using autofacdemo2.Repository;
using System.Web.Mvc;
namespace autofacdemo2.App_Start
{
public class DependencyInject
{
private static IContainer _container;
public static IContainer Container {
get { return _container; }
}
///
/// 注册相关接口
///
public static void Initialise()
{
var builder = new ContainerBuilder();
builder.RegisterType
_container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
}
}
using System.Linq;
using System.Web.Mvc;
namespace autofacdemo2.Controllers
{
public class HomeController : Controller
{
protected internal IStudentRepository GetStudentRepository()
{
return DependencyResolver.Current.GetService
}
public ActionResult Index()
{
var students = GetStudentRepository();
ViewBag.Count = students.GetStudents().Count();
return View(students.GetStudents());
}
}
}
{
public class BasicController : Controller
{
// GET: Basic
protected internal TService GetService
{
return DependencyResolver.Current.GetService
}
}
}
using System.Linq;
using System.Web.Mvc;
namespace autofacdemo2.Controllers
{
public class AutofacTestController : BasicController
{
// GET: AutofacTest
public ActionResult Index()
{
var studentrepository = GetService
ViewBag.Count = studentrepository.GetStudents().Count();
return View();
}
}
}
下一篇:jQuery练习