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());的后面,不然会出现错误:没有为该对象定义无参数的构造函数。

转载于:https://my.oschina.net/u/3911753/blog/3083400

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用 Autofac 进行批量依赖注入时,可以使用 Autofac 的 `RegisterAssemblyTypes` 方法实现。 首先,需要在程序集中标记需要注入的类型,可以使用 `Autofac.Module` 类进行实现。例如: ```csharp using Autofac; public class MyModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<MyService>().As<IMyService>(); builder.RegisterType<MyRepository>().As<IMyRepository>(); // 注册其他需要注入的类型 } } ``` 然后,在 `Global.asax.cs` 文件中,使用 `ContainerBuilder` 类创建容器,并把需要注入的模块注册进去。例如: ```csharp using Autofac; using Autofac.Integration.WebApi; using System.Reflection; using System.Web.Http; public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly()); var container = builder.Build(); GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); } } ``` 这样,就可以实现批量依赖注入了。在需要使用注入的类型时,可以通过构造函数注入或属性注入的方式获取实例。例如: ```csharp public class MyController : ApiController { private readonly IMyService _myService; public MyController(IMyService myService) { _myService = myService; } [HttpGet] public IHttpActionResult MyAction() { // 使用 MyService return Ok(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值