如何实现 在Controller 中 用属性注入,而不是构造函数注入呢,类似下面的代码。
public class HomeController : BaseController { private IUserRepository urep { get; set; } public ActionResult Index() { var cc1 = urep.GetList(); return View(cc1); } }
前提是容器配置在Global里面写。看了很多资料没找到好的办法。
builder.RegisterType<HomeController>().As<BaseController>().PropertiesAutowired()
你好朋友 首先非常感谢你回答,我前提是在Global 里面配置IOC容器,如果按你回答的写法必须要 容器里面的实例操作 var a=container.Resolve<HomeController>(); 所以你的答案不是我想要的。
@请求:
//global.cs var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILog>(); builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
public class HomeController : Controller { public ILog Logger { get; set; } public ActionResult Index() { ViewBag.Message = "欢迎使用 ASP.NET MVC!"; Logger.Log("hello"); return View(); } public ActionResult About() { return View(); } }
@jello chen: 哥 代码看不到 加号点不开
@请求:
var builder = new ContainerBuilder(); builder.RegisterType<Logger>().As<ILog>(); builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
public class HomeController : Controller { public ILog Logger { get; set; } public ActionResult Index() { ViewBag.Message = "欢迎使用 ASP.NET MVC!"; Logger.Log("hello"); return View(); } public ActionResult About() { return View(); } }
@jello chen:
protected void Application_Start() { var builder = new ContainerBuilder(); builder.RegisterType<UserRepository>().As<IUserRepository>(); builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
public class HomeController : Controller { private IUserRepository urep{get;set;} public ActionResult Index() { var cc1 = urep.GetList(); return View(cc1); } }
还是不行,哥们帮我看看那里错了,正常 构造函数注入没问题
@jello chen: 哥们 感谢啊 我靠 我那个属性设为私有的了 换成Public 可以了 尼玛 真的很感谢