CRM Development

Solutionist has designed the architecture for a new CRM system for use in the medical imaging industry.

Tuesday, 7 June 2011

.NET IoC - part 3 (Spring)

It's been some time, but this is continuing my previous posts about .NET IoC.

As I'm familiar with Spring from the Java world, I thought I'd transfer that knowledge across to .NET. It turned out to be less painful than I expected.

I was building a service-based project and used spring on both the client and server sides of the divide. For this post, I'll initially stick to it's use on the client side, but server-side has a very similar set-up. Maybe I'll come to full WCF integration later on.

For basic IoC you just need the Spring.Core.dll from the distribution - add this as a reference to your project.

Initially I'm following the KISS principle, so I created a basic application context file - spring.config.xml and put that at the top level of my project.

Basic format is as follows:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">

<object id="Object1"
type="<Assembly name>.namespace.classname1, <assembly name>" singleton="false">

<property name="Property1"  ref="Object2" />
</object>


<object id="Object2"
type="<Assembly name>.namespace.classname2, <assembly name>" singleton="false">

</object>

</objects>


The singleton="false" will ensure that Spring gives you a new instance every time you request the particular object.

As a minimum in your code, you'll need to create an application context somewhere.
I've put it in a singleton Locator class as follows:

private static IApplicationContext _context = null;
_context = new XmlApplicationContext("spring-config.xml");

where spring-config.xml is the name of your config file. This is sitting at the top-level of the project.

Then you'll want a method to grab hold of an object instance as follows:

public object getObjectInstance(string name)
{
  return _context.GetObject(name);
}

or, if you need to pass arguments in to the constructor...

public object getObjectInstance(string name, object[] args)
{
  return _context.GetObject(name, args);
}

In both cases "name" is the object's ID in the configuration file.
Passing arguments in like this is "OK", but can be a pain, since there's no compile time checking - but we're staying simple.

At some point you could call:

Locator.Instance.getObjectInstance("Object1");


This will:
  • create an instance of Object1
  • create an instance of Object2
  • set Property1 on Object1 to be Object2
  • return you a "ready-to-go" instance of Object1.
 These are your absolute basics. But hopefully this will put you on the road.

No comments:

Post a Comment