0

我有以下接口和基类。

用户存储库:

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”。

4

3 回答 3

1

就我而言,这是因为我在实现接口的类中没有默认构造函数

于 2018-08-02T23:05:27.110 回答
0

对于以后看这个问题的人,还请确保实现类的名称以接口名称开头。

前任:

class FooBarImpl : IFooBar

不是

class Foo : ISomething

于 2021-01-05T23:23:24.240 回答
0

根据您在“更新”中的异常,您需要注册 AuthenticationContext 类,以便温莎知道如何创建它。

container.Register(
    Component.For<AuthenticationContext>()
        .ImplementedBy<AuthenticationContext>());

但是,基于 UserRepository.cs 代码,它依赖于接口 IAuthenticationContext(而不是 AuthenticationContext),因此您可以指定接口的实现:

container.Register(
    Component.For<IAuthenticationContext>()
        .ImplementedBy<AuthenticationContext>());
于 2016-05-06T13:25:13.323 回答