Search code examples
ninjectservicestackormlite-servicestack

Using Ninject with ORMLite


I want to use Ninject with ServiceStack ORMLite but I'm not sure how to configure it.

I have the following in my Repository:

private readonly IDbConnectionFactory _dbFactory;

public TaskRepository(IDbConnectionFactory dbFactory)
{
    _dbFactory = dbFactory;
}

public IEnumerable<Task> GetAll()
{
    using (IDbConnection _db = _dbFactory.OpenDbConnection())
    {
        return _db.Select<Task>();
    }
}

I'm just not sure how to register it to use my connection string. I have bound OrmLiteConnectionFactory to IDbConnectionFactory like so:

kernel.Bind<IDbConnectionFactory>().To<OrmLiteConnectionFactory>().InScope(x => x.Request);

I have also created a new instance of OrmLiteConnectionFactory in the Configure method in AppHost like so:

var ormLite = new OrmLiteConnectionFactory(
    ConfigurationManager.ConnectionStrings["DefaultConnection"]
    .ConnectionString, SqlServerDialect.Provider);

But when I try to use a service I get: ConnectionString must be set

Edit

Here is how I have registered OrmLiteConnectionFactory:

Inside Configure I have:

var ormLite = new OrmLiteConnectionFactory(
ConfigurationManager.ConnectionStrings["AngularApp"]
.ConnectionString, SqlServerDialect.Provider);

// Create Tables and Seed Data
CreateSeedData(ormLite);

IKernel kernel = new StandardKernel();

// Register dependencies in method
RegisterDependencies(kernel);

RegisterDependencies looks like:

private void RegisterDependencies(IKernel kernel)
{
    kernel.Bind<IDbConnectionFactory>().To<OrmLiteConnectionFactory>()
                                       .InSingletonScope();
    kernel.Bind<ITaskRepository>().To<TaskRepository>();
}

Solution

  • IDbConnectionFactory is a db connection factory so it should be a sigleton, i.e. you want to inject the configured instance not create a new one per request, e.g:

    kernel.Bind<IDbConnectionFactory>().ToMethod(c => 
        new OrmLiteConnectionFactory(
            ConfigurationManager.ConnectionStrings["DefaultConnection"]
            .ConnectionString, SqlServerDialect.Provider))
        .InSingletonScope();