thoughts on coding

February 25, 2011

Entity Framework: Problem/Solution of default connection closing !

Filed under: .NET, Entity Framework, NCommon, StructureMap, Uncategorized — Tags: , — Frantisek @ 11:05 pm

I use EF CTP5 on my last project together with NCommon and its UnitOfWork, Repositories, IoC and DI abstracted by MS P&P team and StructureMap as the concrete implemetation of IoC and DI.

Problem :
Let’s have the following example (I took the example from the NCommon unit tests and extend it to do the same Linq query twice):

using (var scope = new UnitOfWorkScope())

{

    var repository = new EFRepository<User>();

 

    User user;

    user = repository.Where(u => u.ComsiID == "login").FirstOrDefault();

    user = repository.Where(u => u.ComsiID == "login").FirstOrDefault();

 

}

 

Just for the completion: creating new UnitOfWorkScope starts the DB transaction. In the above example, using UnitOfWork we create and start the transaction. Then we create new EFRepository instance which creates the ObjectContext. ObjectContext uses the connection identified by the same name AppDb and handles the connection on its own. Then we query the DB. EF opens the connection (this implies that the connection is enlisted into the current running transaction), reads the data and then close the connection. Fine! But then next (in this demo case) same query does the same: opens the connection. Because we run inside the transaction, so the connection is also enlisted into the transaction. And because there was already enlisted connection the transaction mechanism propagates it into DTS.

The result of the above code is that it works and sometimes not! The exception is following:
System.Data.EntityException: The underlying provider failed on Open.
---> System.InvalidOperationException: The connection object can not be enlisted in transaction scope.



THE PROBLEM IS IN ENTITY FRAMEWORK!!!!! and the result of the test depends on the underlying DB. If you use SQLExpress edition (as is used by default in NCommon unit tests), everything works fine! SQLExpress can not elevate the transaction to MS DTC. But if you change the connection to the real SQL server you starts to have the problems.

The problem is that in case you don’t send the concrete connection instance to EF, EF handles the connection status on his own => closes as soon as possible. I understand it but in case of Transaciton is fails! It would be good to have there a switch to configure that behavior. Anyway, the reality is different so how to fix it.

The solution is to manage the connection by your own and while creating the ObjectContext pass already created and open connection. You can find many examples about it on the internet.

Hm, fine but … not so nice. You need manually on all places where ObjectContext, or your class derived from ObjectContext, is used to manage the connection

With NCommon and it’s configuration capabilities you can do the following:

NCommon.Configure.Using(adapter)

    .ConfigureData<EFConfiguration>(config => config.WithObjectContext(

        () =>

        {

            AppDb db = new AppDb();

            if (Transaction.Current != null)

            {

                db.Connection.Open();

            }

            return db;

        }))

.ConfigureUnitOfWork<DefaultScopeUnitOfWorkConfiguration>();

 

 

So you don’t need to do open the connection over and over and on different places. Just configure NCommon on one place and use it. That’s the power of the centralized factory code-enabled configurations. In this case, thanks to StructureMap and NCommon!


Here is my full unit test class (using MS Tests):

[TestClass]

    public class SimpleTests

    {

        public IServiceLocator MyServiceLocator;

 

        [TestInitialize]

        public void Setup()

        {

            var _state = new FakeState();

            var _unitOfWorkFactory = new EFUnitOfWorkFactory();

            var _connectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString;

            _unitOfWorkFactory.RegisterObjectContextProvider(

                () =>

                        {

                            var ctx = new AppDb(_connectionString);

                            if (Transaction.Current != null)

                            {

                                ctx.Connection.Open();

                            }

                            return ctx;

                        });

            var _locator = MockRepository.GenerateStub<IServiceLocator>();

            _locator.Stub(x => x.GetInstance<IUnitOfWorkFactory>()).Return(_unitOfWorkFactory);

            _locator.Stub(x => x.GetInstance<IState>()).Do(new Func<IState>(() => _state));

            ServiceLocator.SetLocatorProvider(() => _locator);

        }

 

        [TestCleanup]

        public void Cleanup()

        {

        }

 

        [TestMethod]

        public void Can_perform_simple_query()

        {

                using (var scope = new UnitOfWorkScope())

                {

                    var repository = new EFRepository<User>();

 

                    User user;

                    user = repository.Where(u => u.ComsiID == "a").FirstOrDefault();

                    user = repository.Where(u => u.ComsiID == "a").FirstOrDefault();

 

                }

        }

I must again say, NCommon and StructureMap rocks!

Happy coding…

Advertisements

August 11, 2010

Book Review: ASP.NET MVC 2 IN ACTION

Filed under: ASP.NET MVC, Di Factory, IoC, MVCContrib, NHibernate, StructureMap, Uncategorized — Frantisek @ 1:36 pm

I read MEAP version of the book ASP.NET MVC 2 in Action from Jeffrey Pallermo last month and I’d like to share my point of the view.

The book shows you how to use ASP.NET MVC 2 in Alt.Net (StuctureMap, MvcContrib, Rhino.Mocks, jQuery, NHibernate, NUnit, etc.) way – which I appreciate very much.

The book shows more how CodeCampServer.org was built connected with ASP.NET MVC 2, what is the logic, tips and tricks behind the designed solution. I must say, I like it as Headspring designed it. I just would call this book ASP.NET MVC 2 in Action on CodeCampServer project.

If you want to download and understand the code quite deeply, read this book. The quys around CodeCamperver are really cool ;o)!

If you want to know more about ASP.NET MVC 2 in general than how to use ASP.NET in Alt.NET, way then read this book: Pro ASP.NET MVC 2 Framework, Second Edition (Expert’s Voice in .NET)

March 11, 2010

StructureMap v2.6.1 released!

Filed under: .NET, Di Factory, StructureMap, Uncategorized — Frantisek @ 9:30 pm

There is new version of really usefull library used for DI, IoC – called StructureMap – released. You can find more about that new version on the blog from Jeremy Miller, here

Jeremy explains what was changed there and what’s new but … we miss the up-to-date documentation ….

It’s really cool library, we use it quite much on our projects and it’s really a killer against other similar libraries (I’ll write a post about it later).  I was looking forward to check the new version and use it but here are my comments:

1) API was changed quite massively and there were made obsolete many methods and few were removed. I must say, that the comments used on the Obsolete attribute are not usefull in all situations the old version was able to be used (see example bellow).

2) The release is missing an up-to-date documentation describing how to migrate from old version to the latest version. The migration to the new version is not very straightforward, IMHO. The package (binaries), which you can download from here contains only binaries ;o), no documentation, no tests (which can act as a kind of the document as well), etc.

Solution

I think the NUnit tests are very good source of the documentation and explanation how to use the explored library and it should be UP-TO-DATE. So for all who wants to migrate to new version of Structure and dont want to wait for the documention or Jeremy’s blogs I propose the following:

download the full package which includes also NUnit tests 😮 from here (scroll down and take the latest commit, it includes more than 11MBs of data) and spend some time with analyzing code and NUnit tests.

My feedback

I really support the libraries with Fluent approach. Structure map has it but I think, some changes, which should be more fluent in the newer version are less fluent now.

Example: AsSingleton() construct replaced with Singleton(), as following:

I think, more fluent version would be:

I think it’s more fluent. I must say it took me a while to find it out, especially when old construct was completely different with AsSingleton() at the end ;o  I know, my suggestion i’s small change, but I would say, it would bring more fluent voice.

Another, but I think, bigger change was related to situation when we want to add the named instances to the container. It’s connected to the class IInstanceExpression<T> and its OfConcreteType<PLUGGEDTYPE>() method like on the following:

The obsolete attribute advice what to use is nice but useless in the situation when we use AddInstances() construct.

In this case we are not able to avoid using OfConcreteType<T>(). There are 2 possible solutions:

The first is to use the For<T1>().Add<T2>.Named(“name”) like on the following picture:

OR

the old way which was used in 2.5.4 version:

and live with the fact that there will be warnings.

I checked the NUnit tests from StructureMap because I wanted to know how to use this construct correctly and I was disappointed that the there is used the OLD version of the solution (the obsolete methods with the warnings) like the following:

Summary

It’s a shame that the release 2.6.1 contains API changes but MANY NUnit tests uses old, Obsolete version of the API. So the documentation is not up-to-date nor the tests.

I think, the team shouldn’t change the API without changing the unit tests to use that new API and thus providing us a solution how to migrate from old  version to the new version.

Anyway, StructureMap is really nice library with many very useful features, going hand in the hand with TDD, Mocking, Plugins, etc. and the biggest advantage is the implementation of Convention over Configuration approach which is unique!

I hope Jeremy will have more free time to blog more about the newest version.

Blog at WordPress.com.