-
Notifications
You must be signed in to change notification settings - Fork 4
Using dependency injection
mtmk edited this page Jun 2, 2011
·
5 revisions
You can use dependency injection with Synoptic by implementing Synoptic.IDependencyResolver which only has one method to resolve dependencies.
You can inject your services into your command classes making them potentially easier to test and maintain.
using System;
using Synoptic;
namespace Demo
{
[Command]
public class MyCommand
{
private readonly IMyService _myService;
public MyCommand(IMyService myService)
{
_myService = myService;
}
[CommandAction]
public void RunMyServices(string message)
{
Console.Out.WriteLine("RunMyServices");
Console.Out.WriteLine(" message=" + message);
Console.Out.WriteLine(" _myService.Hello=" + _myService.Hello(message));
}
}
}
##StructureMap Example
Here is an example of how you could use StructureMap (a popular DI framework) in your projects to enable dependecy injection:
using System;
using Synoptic;
using StructureMap;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
var c = new Container(service => {
service.For<IMyService>().Use<MyService>();
service.For<IMyService2>().Use<MyService2>();
});
var resolver = new StructureMapDependencyResolver(c);
new CommandRunner()
.WithDependencyResolver(resolver)
.Run(args);
}
}
}
To be able to run the code above, you need to implement IDependencyResolver for StructureMap:
using System;
using Synoptic;
using StructureMap;
namespace Demo
{
public class StructureMapDependencyResolver : IDependencyResolver
{
private readonly IContainer _container;
public StructureMapDependencyResolver(IContainer container)
{
_container = container;
}
public object Resolve(Type serviceType)
{
return _container.GetInstance(serviceType);
}
}
}
##Ninject Example
Here is another example of how you could use Ninject:
using System;
using Synoptic;
using Ninject;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
var k = new StandardKernel();
k.Bind<IMyService>().To<MyService>();
k.Bind<IMyService2>().To<MyService2>();
var resolver = new NinjectDependencyResolver(k);
new CommandRunner()
.WithDependencyResolver(resolver)
.Run(args);
}
}
}
To be able to run the code above, you need to implement IDependencyResolver for Ninject this time:
using System;
using Synoptic;
using Ninject;
namespace Demo
{
public class NinjectDependencyResolver : IDependencyResolver
{
private readonly IKernel _kernel;
public NinjectDependencyResolver(IKernel kernel)
{
_kernel = kernel;
}
public object Resolve(Type serviceType)
{
return _kernel.Get(serviceType);
}
}
}