c# – 如何使用Autofac在构造函数中注入特定的实现

我有两个类,它们将ILastActivityUpdator作为构造函数参数:UserService和AnonymousUserService.

public AnonymousUserService(ILastActivityUpdator lastActivityUpdator)
{
    if (lastActivityUpdator == null)
    {
        throw new ArgumentNullException("lastActivityUpdator");
    }
    this.lastActivityUpdator = lastActivityUpdator;
}

和UserService类似,如上所述:

public UserService(ILastActivityUpdator lastActivityUpdator)
{
    if (lastActivityUpdator == null)
    {
        throw new ArgumentNullException("lastActivityUpdator");
    }
    this.lastActivityUpdator = lastActivityUpdator;
}

ILastActivityUpdator接口有一个方法:UpdateLastActivity(int userId).该接口有两个实现,一个LastActivityUpdator和一个名为AnonymousUserLastActivityUpdator的装饰器,它继承自LastActivityUpdator,并为该方法添加了一些额外的功能,如下所示:

public class AnonymousUserLastActivityUpdator 
    : LastActivityUpdator, IAnonymousUserLastActivityUpdator
{
    public AnonymousUserLastActivityUpdator()
    { }

    public override void UpdateLastActivity(int userId)
    {
        base.UpdateLastActivity(userId);

        // Extra functionality
    }
}

我现在想使用Autofac将AnonymousUserService与AnonymousUserLastActivityUpdator和UserService与LastActivityUpdator连接起来.

我尝试的是为从基本接口派生的装饰器添加一个接口,如下所示:

public interface IAnonymousUserLastActivityUpdator : ILastActivityUpdator
{ }

然后我想我可以在AnonymousUserService构造函数中使用IAnonymousUserLastActivityUpdator,所有内容都可以正确自动装配.

不幸的是,它总是使用第一个实现,因为它是早先注册的(字母顺序),因此是IAnonymousUserLastActivityUpdator.

如何实现AnonymousUserService注入AnonymousUserLastActivityUpdator和UserService LastActivityUpdator?

解决方法:

Autofac是nicely documented,看起来你可以在here之后找到你的名字.据我所知,如果你注册了你的更新者

builder.RegisterType<LastActivityUpdator>();
builder.RegisterType<AnonymousUserLastActivityUpdator>();

那么你应该能够注册你的服务

builder.Register(c => new UserService(c.Resolve<LastActivityUpdator>()));
builder.Register(c => new AnonymousUserService(c.Resolve<AnonymousUserLastActivityUpdator>()));

要么

builder.RegisterType<UserService>().WithParameter(
    (p, c) => p.ParameterType == typeof(ILastActivityUpdator),
    (p, c) => c.Resolve<LastActivityUpdator>());

builder.RegisterType<AnonymousUserService>().WithParameter(
    (p, c) => p.ParameterType == typeof(ILastActivityUpdator),
    (p, c) => c.Resolve<AnonymousUserLastActivityUpdator>());

然后,当您从容器中解析UserService或AnonymousUserService时,它们将获得正确的依赖项.

顺便说一句,如果将接口注入到类中,那么该类应该与该接口的所有实现一起正常运行(LSP).从类名称来看,AnonymousUserService看起来只适用于AnonymousUserLastActivityUpdator,而不适用于ILastActivityUpdator的任何实现.如果是这种情况,那么根据您的建议引入不同的抽象(如IAnonymousUserLastActivityUpdator)可能是合适的.

上一篇:c# – 如何将Autofac链接到UnitTesting


下一篇:c# – NInject相当于Autofac的AsClosedTypesOf