首页 > 解决方案 > 在基本控制器 mvc 应用程序中使用 AutoFac 进行属性注入

问题描述

我正在使用 ASP.net MVC 应用程序。我想在基控制器类中注入服务(我不能对 DI 使用构造函数注入)。

我想在基本控制器中使用属性注入。

以下是服务代码:

 public interface IUserService {}
 public class UserService : IUserService
 {
        private readonly IUnitOfWork unitOfWork;
        private readonly IUserRepository userRepo;
        private readonly ILoginAttemptRepository loginAttemptRepo;
        private readonly IRoleRepository roleRepository;
        public UserService(IUserRepository userRepository, 
            ILoginAttemptRepository loginAttemptRepository,
            IUnitOfWork unitOfWork, IRoleRepository roleRepository)
        {
            userRepo = userRepository;
            this.unitOfWork = unitOfWork;
            loginAttemptRepo = loginAttemptRepository;
            this.roleRepository = roleRepository;
        }
 }

以下是 Autoface 全局设置:

private static void SetAutofacContainer()
        {
            var builder = new ContainerBuilder();

            // MVC - Register your MVC controllers.
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
            builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerRequest();

            builder.RegisterAssemblyTypes(typeof(BankRepository).Assembly)
           .Where(t => t.Name.EndsWith("Repository"))
           .AsImplementedInterfaces()
           .InstancePerRequest();

            builder.RegisterAssemblyTypes(typeof(UserService).Assembly)
           .Where(t => t.Name.EndsWith("Service"))
           .AsImplementedInterfaces()
           .InstancePerRequest();

            // Register for filter 
            builder.RegisterFilterProvider();

            //Register for base class
            // builder.RegisterType<IUserService>().PropertiesAutowired();

            // MVC - Set the dependency resolver to be Autofac.
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

基本控制器:

public class BaseController : Controller  
 {
    public IUserService UserService { get; set; }

    //todo: using UserService instance 
 }

我尝试使用 builder.RegisterType().PropertiesAutowired(); 但它没有奏效,任何想法我错过了什么或我该如何实现这一目标?

标签: asp.net-mvcautofac

解决方案


builder.RegisterControllers(typeof(MvcApplication).Assembly)
       .PropertiesAutowired();

参考:https ://stackoverflow.com/a/29536104/3264939


推荐阅读