这个Singelton是否正确实施?

时间:2018-01-20 12:06:05

标签: entity-framework-6 singleton lazy-loading unit-of-work

我的项目实现了Entity Framework(Schema First),具有Unit Of Work和Repository模式。 我希望我的DBcontext只创建一次(因为它应该是),所以我决定创建一个单例类:

//Singleton
public sealed class Context
{
    private static readonly Lazy<Context> lazy =
        new Lazy<Context>(() => new Context());

    public static Context Instance => lazy.Value;

    private Context()
    {
    }

    //TODO: this should be called lazyly!
    public UnitOfWork CreateUnit()
    {
        UnitOfWork uow = new UnitOfWork();
        return uow;
    }

}

我称之为:

    //CREATE
    public static void Insert<T>(T obj) where T : class
    {
        using (UnitOfWork uow = Context.Instance.CreateUnit())
        {
            uow.Repository<T>().Add(obj);
            uow.Commit();
        }
    }

    public static void Update<T>(T obj) where T : class
    {
        using (UnitOfWork uow = Context.Instance.CreateUnit())
        {
            uow.Repository<T>().Attach(obj);
            uow.Commit();
        }
    }

等。等

问题是,CreateUnit方法一直被调用,我希望它只被调用一次,因为我实现了Lazy加载。

我知道我使用“使用”,但我不必,因为我的UoW实现了IDisposible?

UoW和Singleton如何工作(如果可以的话?)

THX

0 个答案:

没有答案