asp.net-mvc - 在基本控制器 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(); 但它没有奏效,任何想法我错过了什么或我该如何实现这一目标?
解决方案
builder.RegisterControllers(typeof(MvcApplication).Assembly)
.PropertiesAutowired();
推荐阅读
- database - Sync SQLite database between two devices in react native
- arrays - 按对象键映射返回 0?
- angular - Angular 11 upgrade from 10 - css :host(.name) where .name is not added to the component
- python - 如何从 python (ModuleNotFoundError) 运行带有 scikit-learn 版本 0.24 的“spherecluster”包?
- typescript - 在打字稿中构建映射的独占类型
- java - 如何将 String.split 转换为 int
- azure - Azure Frontdoor 或流量管理器
- plantuml - 植物。如何创建有限状态机图?
- javascript - 测试antd
- java - 在 SWT/Eclipse RCP 应用程序中使用 ENTER 进行焦点切换