1

I have a project that uses SS (Great framework!!). It is a Rest API. I reference an other project (I am doing this in VS2012) in the same solution that provides an interface. I also have a 3rd project in the same solution that implements this interface. Lets call these projects:

WebAPI Interfaces Engine

WebAPI references Interfaces and Engine. Engine references Interfaces

All is well so far.

I use IOC in appHost (of WebAPI) to register the Interface of the Engine and this works as well.

My issue is that my Engine needs to access the Ormlite database. I have added a reference of ServiceStatck.OrmLight.Mysql to the Engine but the reference is null when referenced in the Engine constructor.

public Engine()
    {
        using (var db = DbConnectionFactory.OpenDbConnection())
        {
            //do db operations
        }
    }

I can access find the database from Webapi. How do I inform engine of the database? I seem to be lost amongst the layers.

I hope this is clear (considering).

Jeff
  • 2,061
  • 4
  • 27
  • 45
  • Did you have a chance to look at [Web Api help page](http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-entity-framework/using-web-api-with-entity-framework,-part-3)? – Dmitry Sevastianov Sep 27 '13 at 17:22
  • Unless I am missing something - that is not my issue. My issue is that in my Engine project I do not have access to the container and thus do not have access to the Registered DbConnectionFactor which is registered in the appHost of the webAPI. – Jeff Sep 27 '13 at 17:32
  • I don't know all that much about SS but from your question it looks like you are trying to create cyclical dependency between WebApi project and Engine project using IoC. I think you'd be better off moving ormLite dependency to engine and keeping its config in WebApi config. – Dmitry Sevastianov Sep 27 '13 at 17:45

1 Answers1

0

If your AppHost (in WebAPI project) is registering adn resolving the Engine / IEngine instance, then you will need to inject the IDbConnectionFactory to your Engine instance.

The best way is via Constructor Injection.

Modify your Engine class to take a dependency on IDbConnectionFactory:

public class Engine : IEngine
{
    IDbConnectionFactory dbFactory = null;

    public Engine(IDbConnectionFactory dbFactory)  // IoC container injects dbFactory
    {
        this.dbFactory = dbFactory;
    }

    public void DoSomething()
    {
        using (var db = dbFactory.OpenDbConnection())
        {
            //do db operations
        }
    }
}

If your dependencies are registered, Engine will have the dbFactory from your main AppHost.

As for project/solution setup, I recommend reviewing the recommended ServiceStack Physical Project Structure (also on SO).

Community
  • 1
  • 1
Raul Nohea Goodness
  • 2,549
  • 23
  • 24