0

SETUP

Ok so I have an application that follows the Onion archetecture approach i.e:

Frontend References > Services and Domain

Service References > Domain and Data

Data References > Domain

Domain References > nothing

I am using the latest version of EF and I am also using Unity as my IOC.

PROBLEM

The service layer of my application accesses the DataContext in the Data layer via an Interface.

public class TestService : ITestService
{
    private readonly IDataContext _context;

    public TestService(IDataContext context)
    {
         _context = context;
    }

    public BaseResponse SomeServiceCall(BaseRequest request)
    {
           _context.Database.ExecuteSqlCommand("SELECT * FROM test");
    }
}

 public class DataContext : DbContext, IDataContext
 {
    public DataContext() :
        base("DefaultConnection")
    {
          Database.SetInitializer<DataContext>(null);
    }

   public DataContext(string connection) :
        base(connection)
    {
        Database.SetInitializer<DataContext>(null);
    }

    public Database Database { get; set; }

    Public IDBContext<Test> Tests {get;set;}
}

 public interface IDataContext
 {
      Database Database { get; set; }

      IDBContext<Test> Tests {get;set;}
 }

I had to expose the Database object in order to get acess to the ExecuteSQL method. But now when I run this in my service, The database object returns a null reference exception and I do not know how to initialize it. Any help would be greatly appreciated!

Josh

2
  • You don't initialize Database object. It is initialized automatically by the context - if your code uses a real context. Btw. you don't need to expose database. You can expose a method on your context interface and wrap the database access in its implementation on your derived context. Commented Mar 17, 2013 at 11:40
  • Oh wow i just had a huge Homer Simpson moment!!! Thanks so much that worked great! Submit as an answer and I will definitely mark Commented Mar 18, 2013 at 20:35

1 Answer 1

1

You don't initialize Database object. It is initialized automatically by the context - if your code uses a real context. Btw. you don't need to expose database. You can expose a method on your context interface and wrap the database access in its implementation on your derived context.

Sign up to request clarification or add additional context in comments.

1 Comment

A user lacking the rep to comment is asking for an example of doing this here. It might be best to update this answer with that example, then close the linked question as a duplicate of this one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.