Autofac手動注入及自動注入示例

private IGradeService _gradeService;
      
        public HomeController(IGradeService gradeService)
        {
            _gradeService = gradeService;
        }

        public ActionResult Index()
        {
            var model = _gradeService.GetAllGrade().ToList();

            return View(model);
        }

修改Global.asax,在Application_Start()方法裏面添加以下代碼,注意引用Autofac、Autofac.Integration.Mvc以及別的引用函數

var builder = new ContainerBuilder();
builder.RegisterType<GradeService>().As<IGradeService>().InstancePerHttpRequest();

var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

//自動注入
var baseType=tyeOf(Idependency);
var assemblys=AppDomain.currentDomain.getAssemblies().tolist();
builder.RegisterAssemblyTypes(assemblys.ToArry())
.where(t+baseTye.IsAssignableFrom(t)&&t!=baseType)
.AsImplementedInterfaces().InstancePerLifetimeScope();

 注意:DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 這個必須放在builder.RegisterControllers(Assembly.GetExecutingAssembly());的後面,否則會出現錯誤:沒有爲該對象定義無參數的構造函數。ui

相關文章
相關標籤/搜索