Creating an instance of an unit of work (NHibernate) I'm trying to figure out how to create a NHibernate UnitOfWork using .NET Core Dependency Injection. I was just hard-coding the connection string before moving it to appsettings.json configuration file. Is this form of creating a UOW in the service.scope valid? 

It works, but I'm not sure if this is the intended way to do it.

Startup.cs

services.AddScoped&lt;IUnitOfWork, UnitOfWorkV&gt;( x=&gt; { return new UnitOfWorkV(Configuration); });




UnitOfWorkV.cs

public UnitOfWorkV(IConfiguration configuration)
        {
            _sessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(configuration.GetSection("ConnectionStrings:ConexionV").Value))
                .ExposeConfiguration(ConfigureNhibernateValidator)
                .Mappings(m =&gt;
                {
                    m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
                    m.HbmMappings.AddFromAssemblyOf&lt;JobQueue&gt;();
                })
                .BuildSessionFactory();
            Session = _sessionFactory.OpenSession();
            Session.FlushMode = FlushMode.Auto;
        }




appsettings.json

{
  "ConnectionStrings": {
    "ConexionV": "Some connection string"
  }
}
In some camps it is not advised to tightly couple your code to framework specific dependencies like IConfiguration.

Based on the shown constructor it looks like the UnitOfWorkV really needs the connection string and not the configuration. That late bound constructor dependency will only be realized when the class is being resolved.

Refactor the  class to depend on what is actually needed.

public UnitOfWorkV(string connectionString) {
    _sessionFactory = Fluently.Configure()
        .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString)
        .ExposeConfiguration(ConfigureNhibernateValidator)
        .Mappings(m =&gt; {
            m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
            m.HbmMappings.AddFromAssemblyOf&lt;JobQueue&gt;();
        })
        .BuildSessionFactory();
    Session = _sessionFactory.OpenSession();
    Session.FlushMode = FlushMode.Auto;
}


And get the connection string at start up, 

var connectionString = Configuration.GetConnectionString("ConexionV");


injecting it explicitly into the class.

if(connectionString == null) //Fail early
    throw new Exception("Missing connection string");

services.AddScoped&lt;IUnitOfWork, UnitOfWorkV&gt;(_ =&gt; new UnitOfWorkV(connectionString));


That way, any validation can be done immediately at startup instead of deferring to when resolving the actually class