问题
I am trying to use the mediator pattern with shortbus(https://github.com/mhinze/ShortBus). Everything goes great except binding it to ninject. There is a structuremap example like so
public BasicExample()
{
ObjectFactory.Initialize(i =>
{
i.Scan(s =>
{
s.AssemblyContainingType<IMediator>();
s.TheCallingAssembly();
s.WithDefaultConventions();
s.AddAllTypesOf((typeof(IRequestHandler<,>)));
s.AddAllTypesOf(typeof(INotificationHandler<>));
});
i.For<IDependencyResolver>().Use(() => DependencyResolver.Current);
});
ShortBus.DependencyResolver.SetResolver(new StructureMapDependencyResolver(ObjectFactory.Container));
}
The above is for a unit test. I want to be able to unit test as well but most of all I just want it to work with the whole project.
There is a NinjectDependencyResolver and this should work with ninject. I just know ninject to poorly to get it straight.
I use Ninject MVC with NinjectWebCommon. And the above code is supposed to work for structuremap so i simply need the equivalent for Ninject.
回答1:
Ninject works a bit differently.
For the IRequestHandler<,> and INotificationHandler<> type bindings you should use ninject.extensions.conventions and do something like:
var kernel = new StandardKernel();
kernel.Bind(x => x.FromThisAssembly()
.SelectAllClasses()
.InheritedFromAny(
new[]
{
typeof(ICommandHandler<>),
typeof(IQueryHandler<,>)
})
.BindDefaultInterfaces());
kernel.Bind<IDependencyResolver>().ToMethod(x => DependencyResolver.Current);
ShortBus.DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
You may need to adapt the following:
FromThisAssembly()--> this means only types of the assembly where you write that line will be bound. You can use another mechanism where you specify in which assemblies to look for yourICommandHandler<>andIQueryHandler<,>types.BindDefaultInterfaces(): See here for an explanation and alternatives.
Also note that my example code is based upon ShortBus.Ninject 3.0.48-Beta. The most current ShortBus stable version is referencing StructureMap.
EDIT: I see that you tagged your question asp.net. Instead of using StructureMap.Ninject and it's NinjectDependencyResolver you are probably better off using Ninject.Web.Common (make sure it's the latest version!) and NinjectDependencyResolver of Ninject.web.mvc.
回答2:
For completeness... don't forget to bind your IMediator
kernel.Bind<IMediator>().To<Mediator>();
Also worth noting that if you use BindDefaultInterfaces() you cannot name your handlers however you fancy. See link posted by BatteryBackupUnit.
来源:https://stackoverflow.com/questions/26206290/binding-mediator-shortbus-with-to-ninject