Search code examples
c#inversion-of-controlioc-containerstructuremapbrighter

Intergrating (ian coopers) Brighter with StructureMap


I am jsut getting to grips with the basics of StructureMap (IoC) and am trying to intergrate the Demo of Brighter which can be found here

https://iancooper.github.io/Paramore/QuickStart.html

With Structuremap within an MVC project.

The issue I am having is working out what to pass into the Structuremap Object factory on build, it is returning

I currently have the following error

An exception of type 'System.ArgumentOutOfRangeException' occurred in StructureMap.dll but was not handled in user code

Additional information: Specified argument was out of the range of valid values.

Factory Handler

public class SimpleHandlerFactory : IAmAHandlerFactory
    {
        public IHandleRequests Create(Type handlerType)
        {
            return new GreetingCommandHandler();
        }

        public void Release(IHandleRequests handler)
        {

        }
    }

The CommandHandler

  public class GreetingCommandHandler : RequestHandler<GreetingCommand>
    {
        public override GreetingCommand Handle(GreetingCommand command)
        {
            Debug.Print("This is the trace for the command :  {0}", command.Name);
            return base.Handle(command);
        }
    }

And my Structuremap Dependency Scope

   public IHandleRequests<T> GetExecutorFor<T>() where T : class, IRequest
        {
            return this.Container.GetAllInstances<IHandleRequests<T>>().FirstOrDefault(); // GetInstance() throws exception if more than one found
        }

And then on the IoC.cs

    public static IContainer Initialize() {
        ObjectFactory.Initialize(x =>
                    {
                        x.Scan(scan =>
                                {
                                    scan.TheCallingAssembly();
                                    scan.WithDefaultConventions();
                                });
                   //  x.For<IHandleRequests<IRequest>>().Use<IHandleRequests<IRequest>>();
// So this is where I was going wrong I should of been doing 
 x.For<IHandleRequests<GreetingCommand>>().Use<GreetingCommandHandler>();
                    });
        return ObjectFactory.Container;
    }

Thanks in advance,

Martyn


Solution

  • To resolve GreetingCommandHandler you would have to register that in your IContainer specifically, because it will not resolve using DefaultConventions.

    For<IHandleRequests<GreetingCommand>().Use<GreetingCommandHandler>();
    

    Should work for you.

    For all other concrete implementations, you would have to do the same.