StructureMap - Scan is a generic interface with a basic implementation and specific
I have an interface something like this:
interface IGenericSetupViewModel<T>
Then I have a default implementation, something like this
class GenericSetupViewModel<T> : IGenericSetupViewModel<T>
For some specific classes, I have a specific implementation like this:
class ContractSetupViewModel : GenericSetupViewModel<Contract>
Now I want StructureMap to return the correct instance by requesting
ObjectFactory.GetInstance<GenericSetupViewModel<Contract>();
I would like the ContractSetupViewModel to return when something else is requested, i would like to get an instance
GenericSetupViewModel<T>
I tried to do this:
StructureMap.ObjectFactory.Configure(x =>
{
x.Scan(y =>
{
y.TheCallingAssembly();
y.AddAllTypesOf(typeof(IGenericSetupViewModel<>));
y.ConnectImplementationsToTypesClosing(typeof(IGenericSetupViewModel<>));
});
});
However, this results in me always getting the GenericSetupViewModel and never working with the ContractSetupViewModel. I don't want to specify all of the specific view modes, so can I still get this scan to work?
source to share
There was a short error in StructureMap where ConnectImplementationToTypesClosing had a problem if your particular closure type did not implement the interface directly. After getting the latest version of StructureMap, the following code will work:
StructureMap.ObjectFactory.Configure(x =>
{
x.Scan(y =>
{
y.TheCallingAssembly();
y.ConnectImplementationsToTypesClosing(typeof(IGenericSetupViewModel<>));
});
x.For(typeof (IGenericSetupViewModel<>)).Use(typeof(GenericSetupViewModel<>));
});
source to share
I'm not too familiar with StructureMap, but could you be fooled by the registration priority?
First you call y.AddAllTypesOf(typeof(IGenericSetupViewModel<>));
, this will register the opene generic class first GenericSetupViewModel<T>
. This registration will fulfill your permission request for GenericSetupViewModel<Contract>
, and the more specific registration ContractSetupViewModel
will be ignored.
However, the Flattener pattern makes it clear that working with an open generic type and specific closed typical type registrations should work. Can you get this template to work with your types?
source to share