views:

44

answers:

1

I am familiar with Ninject and in Ninject you can do something similar to

Bind<ICalendar>().To<MonthCalendar>().WhenInjectedInto(typeof(Roster)).InRequestScope();

I'm not sure how to perform something similar in StructureMap. I need to be able to do this dynamically from my own binding without the use of the generic StructureMap methods. Additionally, I need to be able to do it from inside a Registry class. For example...

For(binding.Source).LifecycleIs(GetLifecycle(binding.Scope)).Use(binding.Destination);

I have looked at stack overflow and codebetter for ideas but can not work out how to do conditional binding as in the aforementioned Ninject example.

A: 

If I interpret your Ninject configuration correctly - the generic solution in structure map would be:

For<Roster>().HttpContextScoped().Use<Roster>()
  .Ctor<ICalendar>().Is<MonthCalendar>();

Edit:

For doing the same thing with fully dynamic registrations instead you should be able to use this:

For(binding.Source).LifecycleIs(binding.Lifecycle)
  .Use(binding.Destination).Child(binding.ChildSource)
  .IsConcreteType(binding.ChildDestination);

For configuring a type registration dynamically you could use a convention:

public class DynamicConvention : IRegistrationConvention
{
        public void Process(Type type, Registry registry)
        {
            TypeRegistrationSettings typeSettings = FindTypeSettings(type);
            if (typeSettings == null)
                return;

            registry.For(typeSettings.Source)
              .LifecycleIs(typeSettings.Lifecycle).Use(typeSettings.Destination);
        }
}

Where FindTypeSettings(type) would look up your own bindings.

The convention is registered with a scan:

ObjectFactory.Initialize(
                c => 
                    c.Scan(s => {
                        s.TheCallingAssembly();
                        s.Convention<DynamicConvention>();
                    })
                );
PHeiberg
Yes your first example was exactly what I was after except that I'd like to do it without generics and from within a registry class. Is this possible?As I load and process bindings in a Registry class I don't want to use a scanning method. There is no non-generic version of your first example available in StructureMap?
Joshua Hayes
See my edit for a new shot on doing the same thing dynamically
PHeiberg
@PHeiberg - That looks like what I'm after. I don't have the code in front of me at the moment though. I will update once I have had a chance to try out your solution. Cheers.
Joshua Hayes