Зависимость не введена в класс замком Виндзор
У меня есть следующие интерфейсы и базовый класс.
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 имеет значение null. Любая идея, что мне нужно настроить, чтобы заставить его правильно вводить хранилище.
У меня есть следующий код установки:
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's
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', которая не была зарегистрирована.
3 ответа
В моем случае это было потому, что у меня не было конструктора по умолчанию в классе, который реализует интерфейс
Для тех, кто рассмотрит этот вопрос позже, также убедитесь, что имя реализующего класса начинается с имени интерфейса.
бывший:
class FooBarImpl : IFooBar
НЕТ
class Foo : ISomething
Исходя из вашего исключения в "UPDATE", вам нужно зарегистрировать свой класс AuthenticationContext, чтобы Windsor знал, как его создать.
container.Register(
Component.For<AuthenticationContext>()
.ImplementedBy<AuthenticationContext>());
Однако, основываясь на коде UserRepository.cs, это зависит от интерфейса IAuthenticationContext (а не от AuthenticationContext), поэтому вы должны указать реализацию интерфейса:
container.Register(
Component.For<IAuthenticationContext>()
.ImplementedBy<AuthenticationContext>());