I am trying out the code from this post on Event Driven Architecture (very interesting by the way). His IOC container is Unity though and I would like to do this using Structure map.
His code is:
public class EventSubscriptions : ISubscriptionService
{
public static void Add<T>()
{
var consumerType = typeof(T);
consumerType.GetInterfaces()
.Where(x => x.IsGenericType)
.Where(x => x.GetGenericTypeDefinition() == typeof(IConsumer<>))
.ToList()
.ForEach(x => IoC.Container.RegisterType(x,
consumerType,
consumerType.FullName));
}
public IEnumerable<IConsumer<T>> GetSubscriptions<T>()
{
var consumers = IoC.Container.ResolveAll(typeof(IConsumer<T>));
return consumers.Cast<IConsumer<T>>();
}
}
I have the following which does not seem to be working:
public class SubscriptionService : ISubscriptionService
{
public static void Add<T>()
{
var consumerType = typeof(T);
consumerType.GetInterfaces()
.Where(x => x.IsGenericType)
.Where(x => x.GetGenericTypeDefinition() == typeof (IConsumer<>))
.ToList().ForEach(x => ObjectFactory.Inject(consumerType, x));
}
public IEnumerable<IConsumer<T>> GetSubscriptions<T>()
{
var consumers = ObjectFactory.GetAllInstances(typeof(IConsumer<T>));
return consumers.Cast<IConsumer<T>>();
}
}
I am obviously not too familiar with Structure Map. Some links or explanation on what I am doing wrong would be really appreciated.
Update:
From Henning's answer, I ended up with -
public class SubscriptionService : ISubscriptionService
{
public IEnumerable<IConsumer<T>> GetSubscriptions<T>()
{
var consumers = ObjectFactory.GetAllInstances(typeof(IConsumer<T>));
return consumers.Cast<IConsumer<T>>();
}
}
And then in my bootstrapping class that is called on application startup I have:
public static void ConfigureStuctureMap()
{
ObjectFactory.Initialize(x =>
{
x.Scan(y =>
{
y.Assembly("Domain");
y.Assembly("Website");
y.AddAllTypesOf(typeof(IConsumer<>));
y.WithDefaultConventions();
});
});
}