asp.net mvc4 简单使用Autofac依赖注入小结

1,首先使用 NuGet下载适当的Autofac版本

文件一,Autofac.3.5.2

文件二,Autofac.Mvc4.3.1.0

1,接口类

public interface IRepository
{
  void GetListCount();

}

2,实现类

 public class Repository:IRepository
    {
        public void GetListCount()
        {
            //return 1;
        }

        
    }

3,控制器

public class HomeController : Controller
    {
       
        private IRepository _iRepository;
        public HomeController(IRepository iRespository)
        {
            _iRepository = iRepository;
        }

        public ActionResult Center()
        {
            ViewBag.Name = _iRepository.GetType().Name;
            return View();
        }
    }

4,在Global中使用autofac依赖注入 

    protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //注册方法1
            //ContainerBuilder builder = new ContainerBuilder();
            //var baseType = typeof(IDependency);
            //var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList();
            //var AllServices =
            //    assemblys.SelectMany(s => s.GetTypes())
            //    .Where(p => baseType.IsAssignableFrom(p) && p != baseType);

            //builder.RegisterAssemblyTypes(assemblys.ToArray());

            //builder.RegisterAssemblyTypes(assemblys.ToArray())
            //    .Where(t => baseType.IsAssignableFrom(t) && t != baseType)
            //    .AsImplementedInterfaces().InstancePerLifetimeScope();


            //Autofac注册方法2
            ContainerBuilder builder = new ContainerBuilder();
            var service = Assembly.Load("Service");
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterAssemblyTypes(service).AsImplementedInterfaces();
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }

注:Assembly.Load("Service") 加载的是名为Service的类库 及加载整个Service实现类

 

最后,其实 Autofac 的使用方式还有很多更进阶的操作,而这一篇只是拿现有项目来导入使用,现有项目并不是特别复杂,所以使用 Autofac 的注册类别设定看起来就蛮简单的,不过 Autofac 也是有比较进阶的操作处理方式,可以在注册类别的使用 Lambda 语法将注册的类别做过滤,节省系统找寻可注册类别的时间,如下:

Assembly.Load("Service").Where(t=>t.Name.EndWith("Service")).AsImplementedInterfaces();
注 where里的Service是加载Service类库中以Service结尾的实现类
posted @ 2015-06-09 16:25  EasyCms-  阅读(535)  评论(0编辑  收藏  举报