c# - Entity Framework - Unit Of Work - Sharing the context -
i'm developing asp.net mvc application using latest entity framework version , have strange behaviour.
i share context through different repositories, way can call savechanges anywhere in project, , changes on repositories being changed.
public unitofwork(idbcontext context) : base(context) { versioningrepository = new repository<versioning>(context, this); settingrepository = new repository<setting>(context, this); siterepository = new versionedrepository<site, int>(context, this); pagerepository = new versionedrepository<page, int>(context, this); layoutrepository = new versionedrepository<layout, int>(context, this); assemblyrepository = new versionedrepository<assembly, int>(context, this); logrepository = new repository<log>(context, this); }
now, when i'm starting application , fire multiple tabs requesting same page @ same time following error might popup:
an exception of type 'system.data.entity.core.entityexception' occurred in entityframework.sqlserver.dll not handled in user code
additional information: underlying provider failed on open.
the inner exception is:
the connection not closed. connection's current state open.
the connection state might change 'closed', 'connecting'. application running , refresh various pages, same error not show anymore, can tell me whe i'm having behaviour?
also, following line can give me 'nullreferenceexception' , don't have clue why happening:
return !query.any() ? null : !query.where(filter).any() ? null : query.first(filter);
after refresh, don't 'nullreferenceexception' neither.
important know i'm using unity instantiate dbcontext , unitofwork.
container.registertype<idbcontext, oxygendatacontext>(); container.registertype<iunitofwork, unitofwork>(new perrequestlifetimemanager());
the iunitofwork interface implement idisposable interface. implemented like:
protected virtual void dispose(bool disposing) { if (disposing) { context = null; } } public void dispose() { dispose(true); }
thanks help.
actually if planning work martin fowler patterns implementing them in wrong way.
- first sole purpose of unit of work aggregate transactional operation write/update , delete 1 logical component
- second, unit of work should not provide knowledge or capabilities of read, breaking 1 of solid principle here, soc (separation of concerns)
- third, working orm , repository. can abstract orm using cqrs, odata or query pattern having many abstract repositories not make sense @ all
- finally, if plan work inversion of control pattern repository should injected. why? because abstract dependencies
for unit of work
public interface iunitofwork { void starttransaction(); void commit(); void rollback(); void save<t>(t entity); void delete<t>(t entity); } public interface irepository { iqueryable<t> get<t>(); singleresult<t> getsingle<t, tkey>(tkey key); }
Comments
Post a Comment