IBackofficeUserService

IBackofficeUserService

AutoFac是否可以具有SingleInstancePerCondition()
我有两个在单个IIS网站上运行的网站,并且我希望有2个接口实例。

protected void Setup(ContainerBuilder builder)
{
    builder.Register(CreateBackofficeUserService)
        .As<IBackofficeUserService>()
        .SingleInstance()
}

private static IBackofficeUserService CreateBackofficeUserService(IComponentContext context)
{
    var siteName = Context.GetSiteName();
    if (siteName == "SiteA")
        return new SiteABackofficeUserService();
    else if (siteName == "SiteB")
        return new SiteBBackofficeUserService();
    else
        return null;
}


public interface IBackofficeUserService
{
}

public class SiteABackofficeUserService : IBackofficeUserService
{
}

public class SiteBBackofficeUserService : IBackofficeUserService
{
}

最佳答案

您可以按名称注册两个实例:

builder.RegisterType<SiteABackofficeUserService>()
       .Named<IBackofficeUserService>("SiteA")
       .SingleInstance();

builder.RegisterType<SiteBBackofficeUserService>()
       .Named<IBackofficeUserService>("SiteB")
       .SingleInstance();


然后访问:

container.ResolveNamed<IBackofficeUserService>("SiteA");

09-29 21:44