我正在使用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(); 但它没有用,任何想法我缺少什么或我怎么能实现这一点?