0
votes

I have created a Unit of work wrapper for my Nhibernate data access methods. I initialise my Session Factory inside the Static Constructor of the UnitOfWork class, hoping to have it initialised once and only once.

public class UnitOfWork : IUnitOfWork
{
  private static readonly ISessionFactory _sessionFactory;
  static UnitOfWork()
    {
        var oracleConfiguration = OracleDataClientConfiguration.Oracle10.ConnectionString(ConfigurationManager.ConnectionStrings[Constants.CONNECTION_STRING].ConnectionString);
        _sessionFactory = Fluently.Configure()
                          .Database(oracleConfiguration)
                          .Mappings(m => m.FluentMappings.Add<MyMap>())
                          .BuildSessionFactory();
    }
}

I then bind this unitOfWork dependency with Ninject Kernel during my application startup and then expect Ninject to resolve it in my data access repository's constructor. (I am using Constructor injection).

public class Module : NinjectModule
{
    public override void Load()
    {
         Bind<IUnitOfWork>().To<UnitOfWork>();
    }                                                                       
}

But after resolution, I could understand that the code inside the static constructor was never executed during object creation and as a result my Nhibernate Session factory is null.

I am definitely sure that I am missing something here. Could some one help me understand what is the correct way to use static constructor in Ninject ?

Thanks

1
You don't need to set your unit of work static. It should work without static keywordOrcusZ
If I don't set it to static, with my current Ninject Binding Configuration, it would result in Ninject IOC creating separate Session Factories for each resolution.Dinny

1 Answers

1
votes

You want your Uow constructor to be executed only once, thus you are declaring it static. Why not, but it should not compile with an access modifier (the public keyword). Static constructor does not accept access modifiers (or arguments). Are you sure your code is valid?

I guess you have actually tried without the invalid access modifier.

I do not know how a type could be used without triggering its static constructor first. Maybe NInject is able of doing that. In such case, just fallback to a cleaner solution: add your session factory to NInject with a singleton life-cycle and appropriate code to instantiate it (basically what your current Uow constructor does), and setup your Uow for having it as a dependency.