【发布时间】:2016-04-30 18:56:38
【问题描述】:
我有以下接口和基类。
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);
}
}
用户服务:
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'。
【问题讨论】:
-
您是否尝试过从
UserService中删除默认构造函数?拥有多个构造函数is an anti-pattern. -
如果我删除构造函数,UserService 将不会被注入到我的控制器中。
-
那么当你删除默认构造函数时会出现什么错误?
-
你删除了哪个构造函数?
-
我更新了我的帖子。我删除了 UserService 中的默认构造函数。如何注册 DbContext 的具体实现?
标签: c# castle-windsor windsor-3.0