Reputation: 3510
I am working with ASP.net MVC app. where I want to inject service in base controller class (I can not use Constructor injection for DI).
I want to use property injection in base controller.
following are service code:
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;
}
}
following are Autoface global setup:
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));
}
Base controller:
public class BaseController : Controller
{
public IUserService UserService { get; set; }
//todo: using UserService instance
}
I tried using builder.RegisterType().PropertiesAutowired(); but it did not worked , Any Idea what I am missing or how can I achieve this ?
Upvotes: 1
Views: 1017
Reputation: 3510
builder.RegisterControllers(typeof(MvcApplication).Assembly)
.PropertiesAutowired();
Ref: https://stackoverflow.com/a/29536104/3264939
Upvotes: 1