Corey Coogan

Python, .Net, C#, ASP.NET MVC, Architecture and Design

  • Subscribe

  • Archives

  • Blog Stats

    • 47,176 hits
  • Meta

Archive for May, 2010

StructureMap + WCF + NHibernate Part 2

Posted by coreycoogan on May 27, 2010

Introduction

In Part 1 of this two part series, I showed what it takes to create a library that will enable Dependency Injection in WCF services by leveraging the extension points in the WCF pipeline. My solution had very slight modifications to what was provided by Jimmy Bogard with plans for extending to allow an NHibernate (NH) Session/Call pattern in WCF utilizing StructureMap (SM).

In this post I’ll show my implementation, derived from the solution posted on Real Fiction, that is built on top of my Wcf.IoC library. This library will be responsible for getting a single ISession opened at the start of each call, injecting it into all dependent classes and then flushing and disposing it at the end of the call.

Why Session per Call?

Session per Call, also known as Session per Request, is the pattern where the application is given the responsibility of opening an ISession (DataContext or other UnitOfWork) and then disposing of it at the end of the call. Some variations of this pattern may also open an ITransaction at the beginning of the call and Commit or Rollback at the end. I prefer to return a status in my service response when something goes wrong, therefore I give the service the responsibility of creating and managing transactions. This way I can catch exceptions and react accordingly.

Employing this technique has several advantages.

  • Once setup, developers don’t have to worry about the ISession and where it comes from.
  • Once setup, developers don’t have to worry about properly disposing of the ISession when they are done with it.
  • If there are unhandled exceptions, the ISession is always disposed.
  • Ensures a single ISession is created and used by the service and component dependencies, thereby reducing resource consumption.

First, a special point of emphasis on the last bullet above, which is very important to get the full benefit of the Session/Call pattern we’re implementing here. For this to work, any classes that depend on an ISession must be configured to have an ISession injected into them (I prefer constructor injection for this). It is important that your components don’t configure ISession resolution, but rather let the application handle this detail. To learn more about configuring components from your application using StructureMap, have a look at this post on the topic.

NHibernate Session Context

To ensure the same NHibernate session is used throughout the WCF service call we’ll need to store the session somewhere. In a web application, this place is typically the HttpContext. In WCF, this is done by creating and adding an extension to the InstanceContext, which is basically a storage area scoped to the instance of the service object.

To do this, we simply implement the IExtension<> interface with a class that is responsible for holding a reference to the call’s ISession object and handles Flush and Disposal when the call is over. My implementation here is just like that of the inspiring post with the exception of my try/catch around the Session disposal.

/// <summary>
/// Holds a reference to an NH ISession and gets cached in the InstanceContext of a
/// WCF call.
/// </summary>
public class NhContextManager : IExtension<InstanceContext>
{
	public ISession Session { get; set; }

	public void Attach(InstanceContext owner)
	{
	}

	public void Detach(InstanceContext owner)
	{
		if (Session != null)
		{
			try
			{
				Session.Flush();
				Session.Dispose();
			}
			catch (Exception ex)
			{
				//log the error but don't throw
			}

		}

	}
}

IInstanceProvider

We’ll use a custom IInstanceProvider to add our Extension into the InstanceContext. This is a very straight forward process, as you’ll see. In Part 1 I showed the custom IInstanceProvider implementation that used SM to create an instance of the requested service. We’ll derive our NH Session-aware InstanceProvider from this one so we can add our extension before resolving the type from SM.

public class NhInstanceProvider : IocInstanceProvider
{
	public NhInstanceProvider(Type serviceType) : base(serviceType)
	{

	}

	public override object GetInstance(InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
	{
		//add the NH Session manager to the context of this WCF request
		var nhSessMgrExtension = instanceContext.Extensions.Find<NhContextManager>();
		if (nhSessMgrExtension == null)
			instanceContext.Extensions.Add(new NhContextManager());

		//let the base handle the IoC resolution
		return base.GetInstance(instanceContext, message);
	}

	public override void ReleaseInstance(InstanceContext instanceContext, object instance)
	{
		var nhSessMgrExtension = instanceContext.Extensions.Find<NhContextManager>();
		if (nhSessMgrExtension != null)
			instanceContext.Extensions.Remove(nhSessMgrExtension);

		base.ReleaseInstance(instanceContext, instance);
	}

}

Setting the NhContextManager.Session Property

The NhContextManager’s Session property is what will be used access the current call’s open ISession object. Remember that the NhContextManager is just our way of storing the ISession in the context of the call. This is where we’ll utilize the ISessionFactory.GetCurrentSession() extension point that was graciously granted to us by NHibernate for things just like this.

NHibernate’s ISessionFactory interface has a method, GetCurrentSession(), intended for getting a contextual instance of a session. Getting this working requires two steps.

First, we must create an implementation of the ICurrentSessionContext interface. This is what NHibernate will use to get an open session when one is requested from the GetCurrentSession() method. The other step is to tell the NHibernate configuration what our implementation of ICurrentSessionContext is so it knows how to respond to GetCurrentSession() calls.

ICurrentSessionContext Implementation

First thing to notice is that the constructor takes an ISessionFactory instance. This is required for getting an open Session the first time. The CurrentSession() method is where all the work is done. First, search extensions on the InstanceContext and find the NhContextManager instance. Now get the Session from the NhContextManager.Session property. If it’s there, we’ll return it. If it’s not there, we’ll open a new one, set it on the NhContextManager object, then return it. This is the nuts and bolts of getting this whole thing working. By delegating the ISession.CurrentSession() method to use the WCF instance context, we are ensuring a single open ISession is used for each WCF service instance, which is created once per call.

public class WcfSessionContext : ICurrentSessionContext
{
	private readonly ISessionFactory _factory;
	public WcfSessionContext(ISessionFactory factory)
	{
		_factory = factory;
	}

	public ISession CurrentSession()
	{
		// Get the WCF InstanceContext:
		var contextManager = OperationContext.Current
			.InstanceContext.Extensions.Find<NhContextManager>();

		if (contextManager == null)
		{
			throw new InvalidOperationException(
				@"There is no context manager available.
				Check whether the NHibernateContextManager is added as InstanceContext extension.
				Make sure the service is being created with the NhServiceHostFactory.
				This Session Provider is intended only for WCF services.");
		}

		var session = contextManager.Session;
		if (session == null)
		{

			session = _factory.OpenSession();

			contextManager.Session = session;
		}

		return contextManager.Session;
	}
}

Setting up NHibernate with our ICurrentSessionContext Implementation

Now we have to tell NHibernate what we want to use to extend the ISessionFactory.GetCurrentSession() method. This may seem a bit goofy, but it works. Before building the SessionFactory, we add a property to the NHibernate.Cfg.Configuration using the necessary magic string and the fully qualified type of our ICurrentSessionContext class.

NOTE: this step would be done by the application in the BootStrapper, where NHibernate initialization should be taking place.

void AddCurrentSessionImpl(NHibernate.Cfg.Configuration config)
{

var sessionContextType = typeof (WcfSessionContext);

            var currentSessionContextImplTypeName = sessionContextType.FullName + ", " +
                                                    sessionContextType.Assembly.FullName;

            var props = config.Properties;
            if(props==null)
            {
                props = new Dictionary<string, string>();
                config.AddProperties(props);
            }

            props.Add("current_session_context_class", currentSessionContextImplTypeName);
}

Configuring StructureMap for ISession Resolution

Since we are relying our StructureMap to handle the Dependency Injection of our services, it must be configured to get our ISession from the ISessionFactory.GetCurrentSession() method. Even though StructureMap is to returning a transient instance, which is the default behavior, we’re trusting our WcfSessionContext to give us the same instance per WCF service call.

The best way to do this is create an SM Registry in our Wcf.NHib library. Our Registry will take an instance of an ISessionFactory. This is required so that our application can configure and initialize NHibernate however the application requires and then let our Wcf.Nhib library handle the specific registration. In this way, the library can be leveraged across any number of WCF services that have their own distinct NHibernate configurations.

/// <summary>
/// A StructureMap registry for telling the container how to resolve an ISession request.
/// This must be instantiated and added to the SM configuration so it has an instance of the
/// SessionFactory to use.
/// </summary>
public class WcfNHibernateRegistry : Registry
{
	public WcfNHibernateRegistry(ISessionFactory sessionFactory)
	{

		For<NHibernate.ISession>()
			.Use(() => sessionFactory.GetCurrentSession())
			;
	}
}

Ensuring the Proper IInstanceProvider Implementation

The lowest level object in our WCF pipeline is the InstanceProvider, which is responsible for creating the instance of our service, fully injected with Repositories, ISession, and whatever else is necessary. To make sure my NhInstanceProvider is used throughout the WCF call pipeline, I’ll want to implement a custom ServiceBehavior, ServiceHost and ServiceHostFactory. Luckily, I can just derive from the classes created in my Wcf.IoC library and override the necessary pieces. This is pretty simple and ensures that my service is both DI-enabled and Session/Call aware.

ServiceBehavior

All I have to do here is construct my NhInstanceProvider.

public class NhServiceBehavior : IocServiceBehavior
{
	/// <summary>
	/// A Func that takes the ServiceType in the constructor and instantiates a new IInstanceProvider.
	/// Defaults to an IocInstanceProvider
	/// </summary>
	public override Func<Type, IocInstanceProvider> InstanceProviderCreator
	{
		get
		{
			return (type) => new NhInstanceProvider(type);
		}
	}

}

ServiceHost

The custom ServiceHost has a little more custom code. We’re going to derive from the IocServiceHost to meet our IoC requirement. We’ll override the ServiceBehavior method where we’ll create an instance of the NhServiceHost. Before we return our instance though, we’ll make one modification.

Since our Session/Call implementation requires that WCF is operating in PerCall mode, let’s make sure that’s always the case by forcing that setting. If we use a stateful mode, we may run into the danger of the same ISession being shared between calls which could lead to all sorts of obvious problems.

To do this, we simply find the ServiceBehaviorAttribute of the service instance. If it’s not there, we’ll add it. Now it’s just a matter of setting the InsntaceContextMode property to InstanceContextMode.PerCall.

public class NhServiceHost : IocServiceHost
{
	public NhServiceHost(Type serviceType, params Uri[] baseAddresses)
		: base(serviceType, baseAddresses)
	{
	}

	public override IocServiceBehavior ServiceBehavior
	{
		get
		{
			var behavior = Description.Behaviors.Find<ServiceBehaviorAttribute>();
			if (behavior == null)
			{
				behavior = new ServiceBehaviorAttribute();
				Description.Behaviors.Add(behavior);
			}
			//force PerCall to ensure a single session is not shared
			behavior.InstanceContextMode = InstanceContextMode.PerCall;

			return new NhServiceBehavior();
		}
	}
}

ServiceHostFactory

The ServiceHostFactory, like the ServiceBehavior, will do nothing more than override the SvcHost property to ensure that the NhServiceHost is used when the IocServiceHostFactory asks for a ServiceHost instance.

public class NhServiceHostFactory : IocServiceHostFactory
{
	protected override Func<Type, Uri[], IocServiceHost> SvcHost
	{
		get
		{
			return (type, uri) => new NhServiceHost(type, uri);
		}
	}
}

Now all we need to do to get our NH Session/Call wired up is edit the markup of our .SVC files and tell it what factory to use.

<%@ ServiceHost
Language="C#"
Service="Service.ProfileService"
CodeBehind="ProfileService.svc.cs"
Factory="Wcf.NHib.NhServiceHostFactory,Wcf.NHibernate"
 %>

What This Gets Us

Now that we’ve jumped through all these hoops, what’s the payoff? We now have the ability to write a service that looks like this.

public class ProfileService : IProfileService
{
	readonly IProfileRepository _repository;
	readonly ISession _session;
	public ProfileService(IProfileRepository repository, ISession session)
	{
		_session = session;
		_repository = repository;
	}

	public ProfileDto GetProfile(int id)
	{
		using(var trans = _session.BeginTransaction())
		{
			var result = _repository.FindById(id);
			return result;
		}
	}
}

Conclusion

In Part 1 we saw how to build off a previous example to enable an extendable IoC-enabled WCF Service solution. This gives us testable services without relying on Poor Man’s DI. In Part 2, we extended the library so we could have not only DI provided by StructureMap but to also leverage NHibernate’s extension points which help us achieve a Session/Call pattern. This solution involved several moving pieces, but in the end they fit together rather nicely and quite cohesively. As you play with the solution you may be surprised first to see that it actually works, but more importantly how much more time you’ll have to devote to the important stuff since you quit worrying about Data Access plumbing.

Posted in Uncategorized | 14 Comments »

StructureMap + WCF + NHibernate Part 1

Posted by coreycoogan on May 26, 2010

WCF + IoC

I’m a big fan of TDD/BDD and leaning on my IoC container of choice, StructureMap (SM), to sort things out at runtime. What I’m not a huge fan of is WCF. It can be a pain to work with the .config spaghetti and it will always add complexity to any design that can do without. There are places where services are warranted and in these cases WCF is usually the prescribed tool.

When working with WCF, I typically relied on Poor Man’s DI to attain a testable service implementation while adhering to WCF’s no-arg constructor requirement. I knew there were ways to DI-enable WCF, but didn’t have the time to get it setup. That changed recently and I had the opportunity to create a library that allows me to let SM manage all my service dependencies with the help of this post from Jimmy Bogard.

WCF + IoC + NHibernate

I’m also a fan of NHibernate and the Session per Request pattern. This makes things relatively easy and safe – the biggest benefit being that you let your web application open an ISession in the beginning of a request and flush and dispose of the ISession at the end of the request. The Repositories and Application Services need only be written to accept an ISession (constructor injection is my preference) and leave the plumbing to the application. Of course this requires configuring your application to manage the ISession and setting up your Container to create the required instances.

Applying this pattern to WCF is a little trickier. Where a web application can manage this from an HttpModule or the HttpApplication (Global.asax), a WCF service may not necessarily be accessed via Http or Https. In this case, we have to manage our Sessions and dependency resolution from a totally different pipeline. For this reason we change our nomenclature from Session/Request to Session/Call – as in a WCF call that could be Net.TCP, HTTP, Named Pipes or MSMQ. To achieve this, I will build on top of the WCF IoC library described above and utilize the contextual Session extension point in NHibernate and the techniques outlined by this post on the Real Fiction blog.

Two Part Series

The solutions will be laid out in 2 blog posts. The first is this one, where I’ll build on Jimmy’s example by providing a base for the WCF NHibernate Session per Call library. The second post, StructureMap + WCF + NHibernate Part 2, is where I’ll actually extend the WCF IoC library to allow for NHibernate Session management.

Extending Jimmy’s Example

First let me say, many thanks to you Jimmy for this post. I always enjoy everything Jimmy writes – he has a great writing style that I find easy to follow. If you aren’t subscribed to Los Techies, where Jimmy blogs, I highly recommend adding it to your feeds and checking out MVC 2 in Action from Manning Press.

I extended Jimmy’s solution relatively slightly. Because I knew I was going to be adding NHibernate support, I gave the WCF extension points in this library the ability to work stand alone or to be subclassed. In this way, I won’t couple services to NHibernate that only need IoC support.

Instance Provider

In WCF, an Instance Provider is a factory that is called upon to create the instance of the service class. WCF gives us the IInstanceProvider interface for creating our own Instance Provider. Nothing too magical here, but this is where we wire in SM to create our service instance by accessing it as a Service Locator. Besides the name change, this code is directly from Jimmy’s post.


public class IocInstanceProvider : IInstanceProvider

{

	private readonly Type _serviceType;

	public IocInstanceProvider(Type serviceType)

	{

		_serviceType = serviceType;

	}

	public virtual object GetInstance(InstanceContext instanceContext)

	{

		return GetInstance(instanceContext, null);

	}

	public virtual object GetInstance(InstanceContext instanceContext, Message message)

	{

		//assumes that the SM has been configured already

		return ObjectFactory.GetInstance(_serviceType);

	}

	public virtual void ReleaseInstance(InstanceContext instanceContext, object instance)

	{

	}

}

Service Behavior

Service Behaviors in WCF do exactly what the name implies – add behavior to services. In this case, we need a service behavior to tell WCF that we want to use our own IInstanceProvider implementation. The bulk of the heavy lifting is done in the ApplyDispatchBehavior method, where we set our custom IInstanceProvider to every End Point on our service.

The main difference here between my implementation and Jimmy’s is my virtual InstanceProviderCreator method used to instantiate my custom IInstanceProvider. I default to the IocInstanceProvider class shown above, but the method is virtual and can therefore be overridden by a derived Service Behavior.


public class IocServiceBehavior : IServiceBehavior
{

	public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
	{
		foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
		{
			var cd = cdb as ChannelDispatcher;
			if (cd != null)
			{
				foreach (EndpointDispatcher ed in cd.Endpoints)
				{
					ed.DispatchRuntime.InstanceProvider =
						InstanceProviderCreator(serviceDescription.ServiceType);
				}
			}
		}
	}

	public virtual void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
	{
	}

	public virtual void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
	{
	}

	/// <summary>
	/// A Func that takes the ServiceType in the constructor and instantiates a new IInstanceProvider.
	/// Defaults to an IocInstanceProvider
	/// </summary>
	public virtual Func<Type,IocInstanceProvider> InstanceProviderCreator
	{
		get
		{
			return (type) => new IocInstanceProvider(type);
		}
	}
}

Service Host

Using a custom Service Host will allow us to add the IocServiceBehavior shown above into the pipeline without needing to configure it in the .config file. In my opinion, that is a major pain and adding the custom Service Host pays for itself with that feature alone.

Once again, my implementation is almost identical to Jimmy’s with the exception of the virtual ServiceBehavior getter. This allows me to derive a custom Service Hosts that may need further modifications and add them to the DI-enabled pipeline.

public class IocServiceHost : ServiceHost
{
	public IocServiceHost(Type serviceType, params Uri[] baseAddresses)
		: base(serviceType, baseAddresses)
	{
	}

	protected override void OnOpening()
	{
		Description.Behaviors.Add(ServiceBehavior);
		base.OnOpening();
	}

	public virtual IocServiceBehavior ServiceBehavior
	{
		get
		{
			return new IocServiceBehavior();
		}
	}
}

Service Host Factory

The Service Host Factory is responsible for creating the instance of the Service Host that will eventually put an instance of the service on the wire when it is called. A custom ServiceHostFactory is used as the starting point of our WCF call pipeline extension. To sum it up as simply as possible, it looks like this:

*.SVC -> ServiceHostFactory -> ServiceHost -> ServiceBehavior -> IInstanceProvider -> Service

My implementation is once again very similar to Jimmy’s with a couple exceptions. First, I offer the virtual SvcHost property for creating an instance of a custom ServiceHost. This will again allow me to plug in a different implementation of a ServiceFactory, which I’ll utilize in my NHibernate solution. Another difference is in how I’m initializing SM. Where Jimmy shows this being done in the constructor of the ServiceHostFactory, I keep Container initialization out of the Factory and allow the application to handle it during startup.


public class IocServiceHostFactory : ServiceHostFactory
{
	/// <summary>
        /// Depending on the app servicehost type, the Container should be initialized during
        /// startup, i.e. HttpApplication.Application_Start or
        /// AppInitialize() (http://consultingblogs.emc.com/matthall/archive/2009/08/18/castle-windsor-and-non-http-protocol-wcf-services.aspx)
        /// </summary>
        public IocServiceHostFactory()
        {
        }
	protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
	{
		return SvcHost(serviceType, baseAddresses);
	}

	/// <summary>
	/// Override to create custom ServiceHost implementation.  Defaults to an IocServiceHost
	/// </summary>
	protected virtual Func<Type, Uri[], IocServiceHost> SvcHost
	{
		get
		{
			return (t,u) => new IocServiceHost(t,u);
		}
	}

}

The ServiceHostFactory is referenced in code or in the markup of an .SVC file and would look like something like this.

<%@ ServiceHost
Language="C#"
Service="Service.DoSomethingService"
CodeBehind=" Service.DoSomethingService.svc.cs"
Factory="Wcf.IoC.IocServiceHostFactory, Wcf.IoC, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
 %>

Configuring StructureMap

I mentioned that I’m letting the application initialize StructureMap during application start up. I also mentioned that I stuck to the WCF pipeline to ensure that this solution would work for Net.TCP or HTTP hosted web sites. This raised the question – where is a common application startup? That answer came from this post from Matt Hall. If you are using IIS 7, you can utilize a static AppInitialize() method in the root App_Code directory. This method gets called at startup from services hosted in IIS or WAS.

A few caveats worth metioning:

  • The class that holds the static AppInitialize() method must have a Build Action of “content”. In other words, the class should be deployed to the server as a .cs file and not compiled into the assembly. If it is compiled, I found it wouldn’t work.
  • If you choose to configure StructureMap from within this method, be aware of using the TheCallingAssembly() method when telling the scan where to look for types. This won’t work here because the class is JIT compiled into its own assembly that won’t contain the other types in your service.
  • For these reasons, I find it preferable to create a Bootstrapper class within my Service project and simply call it’s Initialize() method from within my AppInitialize() method.

A simple Bootstrapper example:

public static class Bootstrapper
{
	public static void Initialize()
	{

		ObjectFactory.Initialize(cfg =>
		{
		    cfg.AddRegistry<ProfileRegistry>();
		});

	}
}

A typical AppInitialize() method located in the App_Code root directory:

public static class AppInitializer
{

	public static void AppInitialize()
	{
	    Bootstrapper.Initialize();
	}

}

Conclusion

We’ve now seen how to hook WCF services up to StructureMap so that it will work with any type of hosting strategy – Net.TCP to HTTP and everything in between. We’ve also seen the extension points where we can add behavior to the IoC-enabled WCF pipeline.

In Part 2, I’ll show you how to build upon the solution provided in this post to create a second library that will utilize StructureMap and NHibernate to implement a Session per Call pattern that can be easily reused – allowing developers to focus on the requirements of the application, not the Data Access plumbing.

Posted in Alt.Net, Architecture and Design, IoC, NHibernate, StructureMap, WCF | Tagged: , , , , | 2 Comments »

Using StructureMap to Configure Applications and Components

Posted by coreycoogan on May 24, 2010

By now it’s probably a pretty safe assumption that any developer who’s worth their salt has at least heard of Inversion of Control (IoC) or Dependency Injection (DI), if not used it at least once. IoC as an architectural concept has many benefits, including testability and helping with Open/Closed Principle compliance. The specifics of DI have been discussed many times over, so consult your friendly neighborhood Google for more on the topic. What I’d like to talk about is the tooling that helps developers achieve IoC in their own systems. The tool is known as a Container and there are many good options to choose from in the .NET space. Top picks include Castle, StructureMap (SM), AutoFac, Ninject and even the very sad entry from Microsoft – Unity.

Why StructureMap?

I’ve had to use Unity at a current gig because it was approved and didn’t require .NET 3.5, but I’ll say right off that Unity is a very simple Container that lacks the features that make working with a Container fun. Granted, we’re using version 1.1, so I can’t speak to some of the enhancements found in 2.0.

I’ve blogged about Castle in the past, which I was using because it came standard in the S#arpArchitecture. Castle is a very good Container, but it has its downfalls. The biggest, in my opinion, is that its fluency is not very intuitive. Despite how many times I’ve used it, I can’t configure an application without looking at a previous example. It just doesn’t seem to flow and feels a bit clunky. It’s still a great tool, so I don’t want to take anything away from all the hard work that has gone into it.

Then there’s StructureMap. What can I say – SM rocks and I actually have fun using it. The fluent DSL flows easily and it is capable of doing everything I’ve ever really wanted it to. Some of my favorite, and most used features, include the default convention, the ease of adding custom conventions, registering open generics and showing what’s been configured. If you haven’t worked with it, have a look and play around with it. Like anything, it will take a bit to learn the ins and outs, but after that it’s pure joy. (NOTE: some of the doc I’m linking to is a bit out of date – the only downside to SM, however, there is plenty on CodeBetter)

Define Components

It is common practice to break different layers into separate components/assemblies/VisualStudio.Net Projects, such as Core, Data, Infrastructure, etc. It is also very common to have components shared throughout the enterprise, such as Inventory, SalesProcessing, Products, etc. This is what I’m referring to as components. Since each component may have its own unique DI requirements, configuring applications to initialize each of those components, as well as itself, can become challenging and when done incorrectly can make applications brittle.

Configuring the Application

The application, in the context of this post, refers to the actual executable – web site, Windows Form, WPF, Console, Windows Service, WCF. When using an IoC Container, the application should always have the responsibility of configuring and initializing the Container. It’s not uncommon to see some developers configuring a Container at the component level because that’s where the knowledge of the component’s dependencies exists. How would the application know about special conventions or nuances that the Container should be handling? The problem with this is the case where the application wants to leverage the Container and swap out one dependency for another.

Equally as painful is the practice of configuring all the components directly from the application. Once a developer gets everything working, the configuration is typically copied/pasted to other applications that use the same components. Now when something changes, someone has the joy of [hopefully] finding all the occurrences of the code in question and pasting a new version on top of it.

Configuring Components

So we don’t want the components to configure themselves in the Container and we don’t want to copy/paste the component configuration in all the consuming applications. How do we do it then? Well I’m glad you asked. The answer is found in StructureMap’s Registry facility.

A Registry in SM is a custom class, derived from the StructureMap.Configuration.DSL.Registry class. This is where the nuts and bolts of an SM configuration should exist. A component can have one or more registries, broken down into any sized unit that makes sense. Maybe the Inventory application has a registry for some common domain services and another for specific communication mechanisms that may vary depending on the type of application.

Here’s an example of a simple component Registry that has a couple specific needs and then relies on scanning and default conventions for the rest.


public class ProfileRegistry : Registry
{
	public ProfileRegistry()
	{
	    ForSingletonOf<IProfileValidator>()
		.Use<ProfileValidator>();

	    Scan(scanner =>
		     {
			 scanner.AssemblyContainingType<IProfileRepository>();

			 //use the default convention
			 scanner.WithDefaultConventions();

		     });
	}
}

Initializing the Application

Now that our components have their own default configurations broken into one or more Registry classes, we need to get that into our Container. As previously mentioned, it is the responsibility of the application to configure and initialize the Container. This is something we generally want to happen only once. This can be accomplished by putting the code to handle the initialization of SM, NHibernate, Logging, whatever, in a BootStrapper that gets called at the application’s entry point. This can be the Global.Application_Start in a web application or inside the Program class of a console or WinForm application.

Initializing Component Registries

So how does the BootStrapper initialize SM with each component registry? With StructureMap, there are actually three common techniques.

By Type

This technique is pretty straight forward and probably suits the majority of cases. In this example, we know what the Registries are and simply add them by type to SM’s configuration during initialization.


public static class Bootstrapper
{
	public static void Initialize()
	{

		ObjectFactory.Initialize(cfg =>
		{
		    cfg.AddRegistry<ProfileRegistry>();
		});

	}
}

By Instance

SM also offers the ability to add a registry to the SM configuration as an instance. This comes in very handy when you have a Registry that requires an instance of some type for its own configuration.

A real-life example of this is when using an NHibernate Session/Call pattern in a StructureMap enabled WCF service (details available in this post). In this case, I want the Wcf.NHibernate registry to tell SM how it should resolve an ISession. In order for this to happen, the Registry will need an initialized ISessionFactory instance, which will be passed to it by the application’s BootStrapper. Once the registry is instantiated, just add it to the SM’s configuration.


public static class Bootstrapper
{
	public static void Initialize()
	{
		ObjectFactory.Initialize(cfg =>
		{
		    cfg.AddRegistry<ProfileRegistry>();

			//get the sessionfactory from another method
		    ISessionFactory sessionFactory = InitFactory();

		    //create the WCF NH Registry
		    var nhWcfRegistry = new WcfNHibernateRegistry(sessionFactory);

			//add the Registry as an instance
		    cfg.AddRegistry(nhWcfRegistry);
		});
	}
}

By Scanning

Last but least, SM Registries can be added to the configuration via scanning. I really like SM’s ability to scan the types specified and apply common and custom conventions for type registration. I won’t go into details here, as the documentation is pretty good in this area.

During a scan, SM can be told to look for all Registry implementations and automatically add them to the configuration using the IAssemblyScanner.LookForRegistries() method. This can come in handy if you are scanning your components from your application. If you have a large number of components, it may be tempting to scan all the application’s assemblies and find registries, but be warned that this can make for a very long startup when you consider the number of types in your third party assemblies, like Log4Net, NHibernate, Castle, etc. Of course, you can always apply a convention to limit which components get scanned, but it’s definitely something to be aware of. Just put some thought into your use of IAssemblyScanner.AssembliesFromApplicationBaseDirectory() and IAssemblyScanner. AssembliesFromPath(path:string).


Scan(scanner =>
{
	 //include this
	scanner.TheCallingAssembly();

	//include the Data component
	scanner.AssemblyContainingType<IProfileRepository>();

	//include all the registries
	scanner.LookForRegistries();

});

Conclusion

Using Dependency Injection/IoC is a great way to build loosely coupled, composeable applications. An IoC Container is a tool that is used to tell your application how it should compose your types by defining the “what” and the “how” of your application’s dependency resolution. StructureMap is one of many available choices of IoC Containers for .NET, but its rich feature set and intuitive fluent DSL have put it at the top of my list.

Many examples and tutorials for StructureMap show how to configure a trivial application where all the types exist within the application or from application specific components. When dealing with components that are shared across the enterprise, it is important to give every consuming application a way to configure SM with their default configuration without copying the code into every application’s startup and without putting the configuration decisions solely in the hands of the component. This can be achieved through the use of the StructureMap Registry, which can be defined as coarse or granular as required at the co

Posted in Alt.Net, Architecture and Design, ASP.NET MVC, C#, IoC, NHibernate, StructureMap, TDD, Uncategorized | Tagged: , , , , , | 2 Comments »

 
Follow

Get every new post delivered to your Inbox.