开发者

Using Entity Framework w/o Global State

I made a small test function for creating an Entity Framework Code-First DbContext instance directly connected to a SQL CE 4开发者_如何学Go.0 file but I really don't like the global state approach. Isn't there a better way to do this, without using DbDatabase static properties?

using System.Data;
using System.Data.Entity;
using System.Data.Entity.Database;
using System.Data.SqlServerCe;

public class SqlCeDb
{
    public static T Instance<T>() where T: DbContext, new()
    {
        DbDatabase.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
        DbDatabase.SetInitializer<T>(new DropCreateDatabaseAlways<T>());
        return new T();
    }
}


Dependency Injection is what a lot of people are doing. You write a class that has a dependency on DbContext (i.e. it's a constructor argument or a property decorated as a dependency), and the IoC (Inversion of Control) container will give you an instance of it when the class is created. Every IoC container I've worked with has a way of registering a single instance (instead of creating a new instance every time).

Popular IoC Containers:

  • StructureMap
  • Unity
  • Ninject

There are others, but these are the ones I see used most often.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜