Search code examples
servicestackormlite-servicestack

How to register IUserAuthRepository when the OrmLiteConnectionFactory is using Named Connections


Here is the appHost configuration code:

OrmLiteConfig.DialectProvider = PostgreSQLDialectProvider.Instance;

var dbFactory = new OrmLiteConnectionFactory();
dbFactory.RegisterConnection("NamedKeyConnOne", new OrmLiteConnectionFactory("ConnOne"))
{
    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
});
dbFactory.RegisterConnection("NamedKeyConnTwo", new OrmLiteConnectionFactory("ConnTwo")
{
    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
});
container.Register<IDbConnectionFactory>(dbFactory); 

and here is the authentication portion:

container.Register<IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())); //Authentication and authorization
container.Resolve<IUserAuthRepository>().InitSchema();

So my question is "How do you go about passing the correct IDbConnectionFactory when there is no default connection string?"

Thank you, Stephen


Solution

  • You can't inject a named IDbConnection connection but you can resolve it from the IDbConnectionFactory which you can access from your services like:

    public class MyServices : Service
    {
        public IDbConnectionFactory DbFactory { get; set; }
    
        public object Any(Request request)
        {
            using (var db = DbFactory.OpenDbConnection("NamedKeyConnOne"))
            {
                //...
            }
        }
    }