Global文件
public class MvcApplication : System.Web.HttpApplication { private static IContainer Container { get; set; } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var builder = new ContainerBuilder(); //根据名称约定(服务层的接口和实现均以Contract结尾),实现服务接口和服务实现的依赖 builder.RegisterAssemblyTypes(Assembly.Load("BLOG.IBLL"), Assembly.Load("BLOG.BLL")).Where(t => t.Name.EndsWith("Contract")).AsImplementedInterfaces().PropertiesAutowired().InstancePerDependency(); // 根据名称约定(数据访问层的接口和实现均以Repository结尾),实现数据访问接口和数据访问实现的依赖 builder.RegisterAssemblyTypes(Assembly.Load("BLOG.IDAL"), Assembly.Load("BLOG.DAL")).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces().PropertiesAutowired().InstancePerDependency(); builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); Container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(Container)); } }
控制器
public class DefaultController : Controller { //属性自动注入 public IProvinceContract ProvinceContract { get; set; } // GET: Default public ActionResult Index() { return View(); } public ActionResult GetProvinceList() { var list = ProvinceContract.GetList(p => p.Id > 0); return Json(list); } }
PropertiesAutowired 属性注入
IBLL
public interface IProvinceContract { /// <summary> /// 获取列表 /// </summary> /// <param name="where"></param> /// <returns></returns> IQueryable<Province> GetList(Expression<Func<Province, bool>> where); }
BLL
public class ProvinceContrator: IProvinceContract { //属性自动注入 public IProvinceRepository ProvinceRepository { get; set; } public IQueryable<Province> GetList(Expression<Func<Province, bool>> where) { return ProvinceRepository.GetList(where); } }
原文地址:https://www.cnblogs.com/xiaonangua/p/10783151.html
时间: 2024-10-08 02:46:44