Null !== Steve

Steve Gentile's Tech Blog – Thoughts and Musings

Archive for the category “IOC/DI”

Using NCommon – Unit Of Work, Repository, etc…

 

***Update***

The NCommon codebase has been moved from CodePlex to Google Code.  You can get this code here:

http://code.google.com/p/ncommon/

Any links below have not been updated

—-

I was looking for a good repository for using Entity Framework in a proof of concept project.  I stumbled upon a project called ‘NCommon’.   The beauty of this framework is that is appears to support Entity Framework, Linq to Sql, and NHibernate.

The basis of NCommon is that it helps build a ‘domain driven’ architecture.  A summary from the link above describes the major parts of NCommon:

NCommon is a library that contains implementations of commonly used design patterns when developing applications. So far NCommon provides the following:

  • Framework for implementing a Unit of Work Pattern
  • Framework for implementing a Repository pattern that utilizes Linq
  • Framework for implementing a Validations and Business Rules
  • Implementation of the Specification pattern using Expressions
  • Utility class to help store application specific data in the Thread Local Storage / Current Web Request and AppDomain Level Storage
  • A Guard class that mimics common guard statements that verify parameter values and throws exceptions if values are not acceptable.

NCommon includes a sample website – done with asp.net mvc.  I setup a ‘test’ (it’s not really a test, more of a ‘ok, looks good, how does it work’)

My sample snippet is a call to retrieve and address entity and update it’s state:

Step one:  Register the Unit of Work and Repository with your IOC container of choice – in this case I use Castle Windsor, you can use any IOC however, since NCommon uses the Microsoft ServiceLocator.  (Here is an example done in Unity)

image

Since I have chosen to try Entity Framework, I’m registering the ‘EFUnitOfWorkFactory’ and the ‘EFRepository’ – again, you could use Linq2Sql or NHibernate here.  The unit of work factory is, of course, in charge of creating the unit of work  :)

Step Two:  This is some underlying plumbing that occurs, I’m telling the ServiceLocator what IOC container I’m using for NCommon, additionally, I’m telling the EFUnitOfWorkFactory what EF DataContext I’m using (‘BistroEntities’ is my ObjectContext for my EF test project):

image

I’ll show in a bit what happens at a asp.net mvc level, but this is the core ‘setup’ involved – this is done once in your application, after that you never look at it again   :)

Now, let’s show how I can use this ‘unit of work’ with a ‘repository’ pattern:

image

First off, I want to define in the code that I’m beginning a unit of work.  Martin Fowler tells us all about ‘Unit of Work’ :

Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.

Obviously we want this in our application !  ( I should say you ‘need’ this – lol)

In my senario above, I’m only making one ‘save’ call, however, I could have a situation where I’m saving a collection of entities – the address, a company update, an employee update, a audit trail save, etc… This is all accomplished through the UnitOfWorkScope – it is handling the underlying Transaction as well.  The UnitOfWorkScope does a lookup to the ServiceLocator to find the corresponding type of unit of work.

Secondly, I’m instantiating a new EFRepository.  In the asp.net mvc sample, you’ll see this will be associated to a controller by using dependency injection.  It would look something like this:

public AddressController : Controller
{
       private readonly EFRepository<Address> _addressRepository
       public AddressController(EFRepository<Address> addressRepository)
       {
              _addressRepository = addressRepository;
…

(Basically, the container handles the instantiation of the repository on your behalf via dependency injection)

The entity is retrieved, updated, and saved.

Notice the Unit of work ‘Save’ call:  This save call is committing the underlying transaction.  If I left this out…the save wouldn’t occur  :)

So, how does this work in the NCommon sample website code?

Obviously the real question is, ‘how do we set this up to use in our application’:

In the asp.net mvc application you must set it up in the global.cs file – where the application starts basically: (note, the NCommon sample code uses NHibernate):

image

I’ll skip over the NHibernate specific parts here, you can download the sample, the key item here is telling the Store about the NHibernate ISession (for EF/Linq2Sql this is ‘similiar’ to your context object):

image

The next section is the registration (again, see the sample code)

image

As with above, you can see the registration of the NHUnitOfWorkFactory and the NHRepository.

These get registered along with the controller registration that asp.net mvc offers as well as the ServiceLocator registration of our container.

Lastly then we move to the controller itself, again, looking at the NCommon sample web application:

image

Since the controller is registered, and the IRepository is registered, this is ‘autowired’ to find in the container the IRepository instance and create it on your behalf.

Lastly, we use it:

image

I think this is a fantastic setup and architecture – I would probably insert a ‘service layer’ in between my controller and my repository however.  (and if you have seen my other posts, I think something like RIA.NET – which I think should be called ‘DomainServices.NET’ comes into play…eventually…)

Thanks to Ritesh Rao for his NCommon library as well as for his help in getting starting with NCommon

Inversion of Control: Unity with WCF

A friend of mine is starting to use Unity with WCF, and I looked up a rather simple but good set of articles on Unity with WCF:

1. Integrating Unity with WCF

2. Unity, WCF, ISS

I’ve personally used Castle Windsor’s WCF facility, but for all intent purposes, they are doing the same thing.

If you aren’t using DI with an IOC, I strongly suggest you learn about it and integrate it into your code.  The benefits are fantastic and help promote good separation of concerns, easier to test your code, etc…

There are plenty of .NET IOC containers available.  Learn more about each below:

Message/Service Bus – Mass Transit

 

I’ve been reading several blogs about event-driven/event broker/message bus.  I have used the Castle Windsor EventWiringFacility which allows you to setup a component to publisher with subscribers defined either in the xml or through the windsor fluent interface.  I have blogged about that here.

Taking this a step further is the concept of an event ‘broker’ or ‘message bus’ – where messages are published to the broker that then can send these to subscribers (in a publish-subscriber setup) without setting up delegates/events for the publisher.  One such message bus available in .net is ‘Mass Transit’.

MassTransit is lean service bus implementation for building loosely coupled applications using the .NET framework.

The lean implementation is supported by the YAGNI principle. By focusing on a tight set of specific concerns, the touch points between Mass Transit and the application are minimized resulting in a clear and concise set of interfaces.

Mass Transit offers a ‘how to get started’ example that shows how rather easy it is to get this setup.  In this example it uses Castle Windsor.

I’m a tad bias (lol) toward Castle Windsor, as I find it easy to setup and use, and quite powerful.  The community offers several options, in this case, Mass Transit has started with Castle Windsor and provides a good set of examples to get started.  Using an IoC container makes it very easy to register components to be used by the message bus.

The next step will be create a sample with a test to get this rolling…  off I go, to the Mass Transit wiki to get it all set up…

Edit:  a good ‘how to get msmq installed’:

http://msdn.microsoft.com/en-us/library/aa967729.aspx

Then, ‘setting up the ‘standard-services’ for Mass Transit’:

http://masstransit.pbwiki.com/Standard-Services

Also, a ‘Using the host service’  –

The Host service allows the easy configuration of a Windows service for handling messages on the service bus

http://code.google.com/p/masstransit/wiki/UsingTheHostService

Architecture Layering Part II

Back awhile ago I made this post on Architecture layering.

Having a service layer in a ASP.NET MVC is a great thing!

Initially I was wrapping Actions with transactional attributes, making calls to the Dao objects, etc… Sure, the dao objects are being injected by my IoC container (Windsor) – which by the way, is very sweet, it’s so transparent that I forget who it creating the objects… I just use the interface… (that is another story)

I show a simple example below, but this sample doesn’t capture where I’ve been able to move business logic back into services – simplifying the controllers.   (Also, it cuts back on any duplication)

Simple example:

MyCustomerController

private readonly ICustomerDao CustomerDao;

ctor : MyCustomerController(ICustomerDao CustomerDao){ this.CustomerDao = CustomerDao;}  //injected

Then on a save:

[Transaction]
public ActionResult Save(string id)
{
     …  CustomerDao.Save(Customer);
}

Instead I’ve moved this into a service layer – now the controllers know nothing about the data access layer:

public class CustomerService : ICustomerService
{
    private readonly ICustomerDao CustomerDao;
    public CustomerService(ICustomerDao CustomerDao){ this.CustomerDao = CustomerDao;}  //injected

    public void SaveCustomer(Customer customer)
    {
         using(ITransaction tran = NHibernateSession.Current.BeginTransaction())
         {
                try….
                CustomerDao.Save(Customer);
                tran.Commit();
                …

         }
    }
}

That is our service – it handles all transactions – where needed – in conjunction with the Dao objects

Now the controller gets an injected CustomerService rather than a CustomerDao.  Notice the Transaction attribute is no longer needed.

MyCustomerController

private readonly ICustomerService CustomerService;

ctor : MyCustomerController(ICustomerService CustomerService){ this.CustomerService= CustomerService;}  //injected

Then on a save:

public ActionResult Save(string id)
{
     …  CustomerService.SaveCustomer(Customer);
}

————-

As far as the IoC goes, I’m doing that all within the Global.cs

ie.

ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(Container));

_container.RegisterControllers(Assembly.Load(“Controllers”));

Then I use reflection to add the Dao’s and the Services’s to the container.  It uses Windsors ‘autowiring’ to handle creation based for dependencies.

WPF Composition Application with ‘Caliburn’ Part One & Part Two

Hadi Eskandari is doing a tutorial series on ‘Caliburn’ a MVC architecture for WPF.  His example includes using Windsor for all the container injection infrastructure needs.

Part I

http://blog.hightech.ir/2008/05/wpf-composite-application-with-caliburn.html

Part II

http://blog.hightech.ir/2008/06/wpf-composite-application-with-caliburn.html

Spring.NET and DI with WebForms

Typically with a tool like Castle Windsor you have to setup the container in the Global handlers. For instance:

public class GlobalApplication : HttpApplication, IContainerAccessor
    {
        private static IWindsorContainer container;

        /// <summary>
        /// Provides a globally available access to the <see cref="IWindsorContainer" /> instance.
        /// </summary>
        public static IWindsorContainer WindsorContainer
        {
            get { return container; }
        }

        #region IContainerAccessor

        public IWindsorContainer Container
        {
            get { return container; }
        }

        #endregion

        public void Application_OnStart()
        {
            container = new WindsorContainer(new XmlInterpreter());
        }


Then on any corresponding page, you can retrieve the container, for example, I tend to create a basepage and access the factory, something like this:

public abstract class BasePage : Page
    {
        /// <summary>
        /// Exposes accessor for the <see cref="IDaoFactory" /> used by all pages.
        /// </summary>
        public IDaoFactory DaoFactory
        {
            get { return GlobalApplication.WindsorContainer.Resolve<IDaoFactory>(); }
        }


This pulls from the config to get the IDaoFactory, ie.

<components>
    <component id="primaryDaoFactory"
               type="FSData.DaoFactory, FSData"
               service="FSData.IDaoFactory, FSData">
      <parameters>
        <connectionString>#{connString}</connectionString>
      </parameters>
    </component>
  </components>

Inside the page, I would then use that factory:

IMissionDao dao = DaoFactory.GetMissionDao();

With Spring.NET’s Spring.Web this is all diverted into the configuration with no code required:

First, you setup the correct context – notice I’ve commented out the default context to instead using the webcontext:

<sectionGroup name="spring">
            <!--<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>-->
      <section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web"/>
            <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
        </sectionGroup>

A description of this can be found in the Spring.NET help:

"The instantiation and configuration of the Spring.NET IoC container by the Spring.Web infrastructure is wholly transparent to application developers, who will typically never have to explicitly instatiate and configure an IoC container manually (by for example using the new operator in C#). In order to effect the transparent bootstrapping of the IoC container, the Spring.Web infrastructure requires the insertion of the following configuration snippet into each and every Spring.Web-enabled web application’s root Web.config file"

Next, you add the HttpHandler:

<httpHandlers>
      <add verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/>
        </httpHandlers>


and HttpModule:

<httpModules>
      <add name="SpringModule" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
    </httpModules>

(Both of these are in the web.config)

Once these are setup once, you don’t have to worry about it again.

Now we need to actually use our DaoFactory in our page:

<spring>
        <context>
            <resource uri="config://spring/objects"/>
        </context>
        <objects xmlns="http://www.springframework.net">
            <description>An  example that demonstrates simple IoC features.</description>

      <object type="Default.aspx">
        <property name="DaoFactory" ref="primaryDaoFactory"/>
      </object>

      <object  name="primaryDaoFactory"
               type="FSData.DaoFactory, FSData">
        <constructor-arg name="connectionString" value="server=.SQLEXPRESS;database=dbFW;Integrated Security=true"/>
      </object>

        </objects>
    </spring>


This shows that the Default.aspx page has a dependency on ‘DaoFactory’ that will be injected into the page. I setup a property on the page:

public partial class _Default : System.Web.UI.Page
    {
        private IDaoFactory daoFactory;

        public IDaoFactory DaoFactory
        {
            set { daoFactory = value; }
            get { return daoFactory; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            IAircraftDao acDao = daoFactory.GetAircraftDao();
            List<Aircrafts> ac = acDao.SelectAllAircraft();
        }
    }

* Update:

If you notice, I did have to add the ‘object type=Default.aspx’ above.  Well, let’s say you had a ton of pages and didn’t want to add every page in order to inject this daoFactory.  An alternative is to use a basepage class that inherits from Spring.Web.UI.Page with the following:

        private IDaoFactory daoFactory;
        public IDaoFactory DaoFactory
        {
            get
            {
                //return this.ApplicationContext.ConfigureObject(this, typeof(IDaoFactory).FullName);
                return daoFactory;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            daoFactory = (IDaoFactory)this.ApplicationContext.GetObject("primaryDaoFactory");
            base.OnInit(e);
        }

Since i want the DaoFactory to be a singleton and it’s scope to be the application, I updated the config as well:

<object  name="primaryDaoFactory"
           type="FSData.DaoFactory, FSData" scope="application" singleton="true">
    <constructor-arg name="connectionString" value="server=.\SQLEXPRESS;database=dbFW;Integrated Security=true"/>

This allows me to inject the DaoFactory into every page that uses the base class (granted I’ve probably not want this code in my code behind but that is another topic…)

So there you have it – the daoFactory is injected into the page, and is accessible. I find this to be a better approach than Castle Windsor once you get through the configuration aspects. Both however, are very powerful, so if anything, this shows an alternative way of handling DI in webforms.

Side note: Curious about Spring.NET with MS MVC ? Here is an approach one programmer has used…

also http://fredrik.nsquared2.com/ViewPost.aspx?PostID=465

Collection of Links

Or rather a ‘what have you been doing lately’?

As usual I’m exploring areas around IoC/DI containers, jQuery, and MS MVC.

I had a chance this weekend to plug in some MS MVC time and I’m happy with the results. This is the way that web apps should be built. No question in my mind. There is a reason that MVC has carried over the years. The ability to setup REST urls in the routing, controller first capability of wiring up objects to the view, and Html ‘helpers’ using the new .net extensions is too much to resist. The only issue I’ve run into so far is with REST urls and encoding/decoding. In my sample at home, I have a value of 4.JG53/Recon – the ‘slash’ here messes up the REST.

…/ShowPilots/4.JG53/Recon <- doesn’t work.

I tried encoding it to be 4.JG53%2Recon – but it takes that and decodes it back to the slash – oops. I’m investigating this one, outside of saying ‘don’t pass names like that’ :)

What I find interesting is that I used to struggle of ‘but webforms have these nice controls…’. enough of that garbage. Actually, they are rather over complicated to do simple things. The answer: javascript frameworks. Ext, jQuery, Yahoo, etc… all have rich javascript/CSS controls that do more than the .net controls. Take a tab control. Piece of cake with jQuery/Yahoo. No ‘atlastoolkit’ to fumbled around with. On top of that, browser support is always a key for these guys, they can’t publish javascript frameworks that only run on IE…. (MS…wake up!) :)

Lastly, back to IoC. My links today will show an example of how to build your own. Sure, it’s just a start, but it’s a good way to show the underpinnings of IoC. Microsoft P&P team released Unity in beta, it still has work to do in my opinion. The use of attributes for setter injection is just wrong to me. I don’t want to decorate my classes showing setter injection. To me, it shouldn’t be in my POCO classes. I’d rather wire them up in xml, than place that on my classes. Secondly, for the life of me I cannot find out how to set default values – ie. I pass in the connection string to my dao objects. I’ve used the container to store my connection string, setting it on the constructor. I cannot find this in Unity – maybe I’m missing something :) So, when it came time to do the MS MVC, I ended up switching back to Castle’s Windsor. It’s just so rich and so easy at the same time that it’s too hard to resist.

Ok, on to the links:

IoC:
Build Your Own Container – Part I
Build Your Own Container – Part II

MS MVC
MSContrib – very nice user community contributions including support for Windsor, Spring – new view engines, etc..

MS MVC – Design Philosophy
MS MVC Toolkit
Scott Guthrie’s 5 Part – how to’s (excellent starting place)
Part I – What is It?
Part II – Building an MVC Application
Part III – URL Routing
Part IV – Passing ViewData from Controllers to Views
Part V – Handling Form Edit and Post

jQuery
Using JQuery with MS MVC

Just a simple example – but it shows how simple this is. So much better than dealing with the webforms leaky abstraction, id munging, complex postbacks, etc…

Enjoy!

Unity Dependency Injection Container

The February CTP of the new Unity IOC has been released.

UnityDependencyInjectionContainerReleasedFebruary2008CTP

I need to play with this, but it could be a good alternative to Spring/Windsor. I’m glad to see the Enterprise P&P release this, as I hope it means more adoption by Microsoft shops to using Dependency Injection with a container.

David Hayden has a short but good blog post on using Unity with the MVC.NET

The official CodePlex site has a short writeup of Unity, as well as links to the download

Good stuff :)

ASP.NET MVC Framework and Spring.NET

Great blog post here – this is but one of the parts of the MVC Framework I’m looking forward to!

public IController CreateController(RequestContext context, Type controllerType)
        {
            IResource input = new FileSystemResource(context.HttpContext.Request.MapPath("objects.xml"));
            IObjectFactory factory = new XmlObjectFactory(input);

            return (IController)factory.GetObject(controllerType.Name);
        }

This is quite impressive. This is very straightforward and simple to grasp. Later it shows here

protected void Application_Start(object sender, EventArgs e)
{
   ControllerBuilder.Current.SetDefaultControllerFactory(
                           typeof(MvcApplication.Models.Infrastructure.SpringControllerFactory));
   ...
}

how easy it is to setup your own controller factory.

The attention that MS is paying to allowing Spring.NET/Windsor, etc… to use MS MVC is music to my ears.

What I’m not looking forward to: convincing coworkers who only know Webforms what the value of all this is. Sometimes I feel like I’m the only guy on the island… :)

Post Navigation

Follow

Get every new post delivered to your Inbox.