我有以下接口和基类。Castle Windsor没有注入类的依赖关系
UserRespository:
public class UserRepository : Repository<User>, IUserRepository
{
public IAuthenticationContext authenticationContext;
public UserRepository(IAuthenticationContext authenticationContext)
:base(authenticationContext as DbContext) { }
public User GetByUsername(string username)
{
return authenticationContext.Users.SingleOrDefault(u => u.Username == username);
}
}
UserService:
public class UserService : IUserService
{
private IUserRepository _userRepository;
public UserService(IUserRepository userRepository)
{
_userRepository = userRepository;
}
public IEnumerable<User> GetAll()
{
return _userRepository.GetAll();
}
public User GetByUsername(string username)
{
return _userRepository.GetByUsername(username);
}
}
现在,当我注入UserService它的_userRepository为空。 任何想法我需要配置让它正确注入存储库。
我有以下安装代码:
public class RepositoriesInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Types.FromAssemblyNamed("DataAccess")
.Where(type => type.Name.EndsWith("Repository") && !type.IsInterface)
.WithServiceAllInterfaces()
.Configure(c =>c.LifestylePerWebRequest()));
//AuthenticationContext authenticationContext = new AuthenticationContext();
}
}
public class ServicesInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Types.FromAssemblyNamed("Services")
.Where(type => type.Name.EndsWith("Service") && !type.IsInterface)
.WithServiceAllInterfaces()
.Configure(c => c.LifestylePerWebRequest()));
}
}
我怎么会去注册的具体的DbContext的
public class AuthenticationContext : DbContext
{
public AuthenticationContext() : base("name=Authentication")
{
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
}
UPDATE
当我删除默认UserSe中的构造函数起动转矩大,我得到以下错误:
Castle.MicroKernel.Handlers.HandlerException: Can't create component 'DataAccess.Repositories.UserRepository' as it has dependencies to be satisfied. 'DataAccess.Repositories.UserRepository' is waiting for the following dependencies: - Service 'DataAccess.AuthenticationContext' which was not registered.
你有没有尝试删除默认的构造函数来自'UserService'?拥有多个构造函数[是一种反模式](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=97)。 – Steven
如果我删除构造函数,UserService将不会注入到我的控制器中。 – Wilds
那么当你删除默认的构造函数时你得到的错误是什么? – Steven