Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFac - SingleInstance per dependency

Is it possible with AutoFac to have a SingleInstancePerCondition(). I have two websites who run on a single IIS website and I would like to have 2 instances of my interface.

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
{
}
like image 664
Kapoue Avatar asked Dec 06 '25 10:12

Kapoue


1 Answers

You could register two instances by name:

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

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

and then access:

container.ResolveNamed<IBackofficeUserService>("SiteA");
like image 188
Michael Mairegger Avatar answered Dec 07 '25 22:12

Michael Mairegger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!