CRM Development

Solutionist has designed the architecture for a new CRM system for use in the medical imaging industry.
Showing posts with label IoC. Show all posts
Showing posts with label IoC. Show all posts

Monday, 16 July 2012

Asynchronous WCF using the generated service interface

Using Asynchronous WCF in an IoC style presents an interesting challenge.


Normal examples show that you can call async WCF something like this...
      Service1Client iService1 = new Service1Client();
      iService1.GetDataCompleted += iService1_GetDataCompleted;
      iService1.GetDataAsync();



i.e. you declare the service client implementation, specify the callback and make the async call.


But... what if you want to inject the client reference, for example (using Ninject):
[Inject]
IService1 iService1 {get; set;}

where Service1 is the interface.
Well, you find that the xxxCompleted event and xxxAsync method are not available on the interface. Ouch!
But, all is not lost...
You do have two other methods... Beginxxxx and Endxxxx and you can use them as in the example below. In the Beginxxxx method you specify the callback and in the callback you can get hold of the result by calling Endxxxx


Note that in the example below, I haven't injected the Service client, but I am using the interface, IService1. The code produces the following output (with the "Waited" appearing after the calling thread has slept for 5 seconds) :

    Making call
   Got result
   You entered: 200
   Waited

    public class Program
    {
        private static void Main(string[] args)
        {
            MakeAsynchronousCall(200);
        }
 
        private static void MakeAsynchronousCall(int value)
        {
            IService1 iService1 = new Service1Client();
 
            AsyncCallback aSyncCallBack =
                delegate(IAsyncResult result)
                    {
                        try
                        {
                            Console.WriteLine("Got result");
                            var i = iService1.EndGetData(result);
 
                            Console.WriteLine(i);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    };
 
            try
            {
                Console.WriteLine("Making call");
                iService1.BeginGetData(value, aSyncCallBack, iService1);
 
                Thread.Sleep(5000);
 
                Console.WriteLine("Waited");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

The Server-side code is :
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

Wednesday, 22 February 2012

Architecture Note

A short note on architectures for WCF-based solutions - we've found this works for us.


All classes that are being passed across the wire must be serialisable and each property must be annotated.

The WCF service is nothing more than a thin facade on top of a call to Business Logic. 
In fact it's a one-to-one relationship to the Business Logic calls... The Service layer just exposes the business logic so that it can be used in creating bindings, etc.


Business Logic - as they say, it "does the business" and calls the data access.layer.
Data Access Layer - we're using Repository pattern with Entity Framework.

Throughout, we've using IoC (Ninject) to hook data access repositories into the Business Layer and Business Logic into the Service Layer. This has meant inserting Ninject into the WCF factory pipeline - see this post.

OK, you may ask why create a WCF facade on top of the business logic?

Well, doing this lets you create clean classes and "unit" tests for the business logic without  bothered about annotations, etc for WCF.
It also means that the Business Logic layer becomes a re-usable component - where you don't have to include WCF-related annotations and dlls.

Wednesday, 1 February 2012

More .NET IoC - Using Ninject in WCF Services

I've seen other postings about this, but thought I'd add my own 2p-worth since I had to struggle a bit to get it working.

The basic idea is to use Ninject in the WCF pipeline and get WCF use Ninject to create the service. Then you can take advantage of Ninject's IoC to manage dependencies.

I used the base Ninject and the Ninject Web and Wcf extensions - all available via NuGet.

To integrate ninject into the WCF service pipeline, create a "normal" WCF service but add the following to the .svc file

Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory" 


So, the file would look something like:


<%@ ServiceHost Language="C#" Debug="true" Service="WcfService.GeneralService" 
CodeBehind="GeneralService.svc.cs" 
Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory" %>


Then you can inject dependencies into the service as needed as follows:


[Inject]
public IUsersRepository _repository { private get; set; }

Now we're assuming that you're using a WCF application project - so, to initialise Ninject correctly you need to make changes to the WCF project Global.asax file as follows:


  1. Make Global extend NinjectWcfApplication   (from Ninject.Extensions.Wcf)
  2. Implement and override CreateKernel - so the file looks like this:

    public class Global : NinjectWcfApplication

    {
    // Other methods omitted for clarity...
 
        protected override Ninject.IKernel CreateKernel()
        {
            IKernel k =  new StandardKernel(new ServiceModule());
            return k;
        }
    }


Now the ServiceModule is a Ninject module that would look something like:


    public class ServiceModule : NinjectModule
    {
        public override void Load()
        {
            Bind().To();
        }
    }


Notice that we're binding the IUsersRepository to the UsersRepository implementation.

Doing this will enable Ninject to do its magic in the WCF service above where it is injected.

When Service is invoked, the Ninject factory will instantiate the class and so be able to use the module bindings to pull in the correct interface implementations.

Notice that you don't need to change service bindings, etc. 

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.

Wednesday, 12 January 2011

.Net IoC - part 2 (StructureMap)

It's been some time since I've last posted anything up, but I thought I'd put up a bit more about my
working with IoC in .NET.

In a previous post I mentioned that I'd come across Spring.NET, Unity and StructureMap
I wanted something that I could pick up easily and which focused on IoC. 


Starting to using it fairly simple. 
  1. You reference the structuremap dll
  2. Add something looking like this into your code... I wrapped it up in a Singleton to give me more flexibility.. 
public sealed class Locator     {
        private static volatile Locator _instance = null;         private static object syncRoot = new Object();


        private static Container objectFactory = null; 
        private Locator()
        {
            objectFactory = new Container(
                 x =>
                 {

                    x.For<myservice>().Use<myserviceclient>();                        </myserviceclient></myservice>
 
                     x.For<ihelper>().Use<realhelper>();
  
                     x.For<iinterface1>().Use<implementation1>()
                         .Setter().IsTheDefault();
                 });
        }
 
        public static Locator Instance
        {
            get 
            {         
                if (_instance == null) 
                {            
                    lock (syncRoot)             
                    {               
                        if (_instance == null)                   
                            _instance = new Locator();            
                    }         
                }         
                return _instance;      
            }
        }
 
        public object getObjectInstance()
        {

            return objectFactory.GetInstance();
        }
 

        public object getObjectInstance(Dictionary items)
        {

            var args = new ExplicitArguments();
 
            foreach (var item in items)
            {
                //args.Set(item);
                args.SetArg(item.Key, item.Value);
            }
            return objectFactory.GetInstance(args);
        }


In code I'm calling:
Locator.Instance.getObjectInstance()


The second method allow you to pass in constructor parameters.


All this means I can remove references to StructureMap from my Code and, if need be,
swap out IoC containters without affecting the rest of the code. In fact, this happened eventually.

StructureMap looked a good candidate, the fluent interface is nice and there's no XML if you don't want it! But, I did find the that the lack of decent documentation was an issue.
There was a lot of information - but scattered around. I didn't want to spent ages hunting stuff down.


Unity, I'm afraid, seemed over complicated. I'm still getting my head round other .Net stuff and I wanted to minimise the amount to learn. 


That left Spring.... which, all being well, I'll cover in part 3.

Wednesday, 4 August 2010

.NET IoC

Blogging is a new departure for me, but now I've started my own company (Solutionist) - it seemed like a good time to start... so here goes...

I've been working a lot with .NET technologies lately and have been trying to pull across my
existing Java/J2EE knowledge as a frame of reference.

Something that was sorely missing was Dependency Injection - I'd become fairly hooked on Spring for that and was really missing it in Microsoft World. So, finding Spring.NET and Microsoft's own Unity framework has come as a bit of a relief. Now it's just a case of seeing which one "fits" better.

Hopefully, over the next few days as I try them both out, I'll write it up.