通过Dll实现全部类的属性注入,该演示实例主要通过多层架构中单一的对象方式来演示,没有采取接口的方式, 新建AutoFacHelper类,如下代码:
1 public class AutoFacHelper 2 { 3 private static IContainer _container; 4 5 public static void InitAutofac() 6 { 7 var builder = new ContainerBuilder(); 8 9 //注册数据库基础操作和工作单元 10 11 12 13 //注册app层 14 15 16 builder.RegisterAssemblyTypes(Assembly.Load("MCFrame.Application")).Where(x => x.Namespace == "MCFrame.Application").PropertiesAutowired(PropertyWiringOptions.PreserveSetValues); 17 // .AsImplementedInterfaces().InstancePerLifetimeScope(); 18 19 20 21 22 //注册Repository 23 builder.RegisterAssemblyTypes(Assembly.Load("MCFrame.Repository")).Where(x => x.Namespace == "MCFrame.Repository"); 24 //.AsImplementedInterfaces().InstancePerLifetimeScope(); 25 26 27 builder.RegisterControllers(Assembly.Load("MCFrame.Controllers")).PropertiesAutowired(); 28 29 30 _container = builder.Build(); 31 32 DependencyResolver.SetResolver(new AutofacDependencyResolver(_container)); 33 34 35 36 } 37 38 /// <summary> 39 /// 从容器中获取对象 40 /// </summary> 41 /// <typeparam name="T"></typeparam> 42 public static T GetFromFac<T>() 43 { 44 return _container.Resolve<T>(); 45 // return (T)DependencyResolver.Current.GetService(typeof(T)); 46 } 47 }
在nuget包搜素autofac和autofac.mvc5包安装下载,将需要注入的dll都拷贝到web层bin目录下,
PropertiesAutowired表示通过属性的方式注入
Web层Controller代码如下
1 public class HomeController : Controller 2 { 3 4 public UsersApp app { get; set; } 5 // public UsersRepository dal { get; set; } 6 7 public string Index() 8 { 9 10 11 12 UsersEntity model = new UsersEntity(); 13 model.ID = Guid.NewGuid(); 14 model.UserName = "test"; 15 model.UserPwd = "1232"; 16 model.AddTime = DateTime.Now; 17 app.AddInfo(model); 18 19 return ""; 20 } 21 }
Application(BLL)层代码如下
1 public class UsersApp 2 { 3 4 public UsersRepository dal { get; set; } 5 public void AddInfo(UsersEntity entity) 6 { 7 8 // UsersRepository rp = new UsersRepository(); 9 dal.SaveEntity("", entity); 10 } 11 }