我有以下接口和基类。
用户存储库:
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);
}
}
用户服务:
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; }
}
更新
当我删除 UserService 中的默认构造函数时,出现以下错误:
Castle.MicroKernel.Handlers.HandlerException:无法创建组件“DataAccess.Repositories.UserRepository”,因为它需要满足依赖关系。“DataAccess.Repositories.UserRepository”正在等待以下依赖项: - 未注册的服务“DataAccess.AuthenticationContext”。