views:

38

answers:

1

Ok so this might not be the best title but I am struggling with how to title this. Here is what I have thus far:

I currently have data mappers for my objects. I define them in a registry like so. This allows me to get the type name of the object and combine that with the word Mapper and request it. Here is the code I am using:

this.For<ICategoryMapper>()
    .Use<CategoryMapper>()
    .Named("CategoryMapper");

But now I am having a problem getting the instance from StructureMap in a form that I can use. Because I can't request it like normal with code like this:

ObjectFactory.GetNamedInstance<T>(namedInstance);

The reason being that I don't really know the type. I just know that it should be DomainType name plus the word mapper. There is probably a better way to achieve this but I am at a lost at what to do.

Any input into a better way to achieve this or fix the problem I am having would be great.

+2  A: 

Do you need to use named instances, or was that just an attempt to get it to work?

One approach you could do is add a marker interface that declares the DomainType a mapper works with. For example:

public class PersonMapper : ICategoryMapper, ICategoryMapper<Person>{
}

Register the mappers with the container:

ObjectFactory.Initialize(x =>
{
    x.Scan(scan =>
    {
        scan.TheCallingAssembly();
        scan.ConnectImplementationsToTypesClosing(typeof (ICategoryMapper<>));
        scan.AddAllTypesOf<ICategoryMapper>();
    });
});

You can then retrieve the mapper for your a DomainType (Person, for example):

ObjectFactory.ForGenericType(typeof(ICategoryMapper<>))
  .WithParameters(typeof(Person))
  .GetInstanceAs<ICategoryMapper>();
Joshua Flanagan
+1 Yes using named instances was just a way that I could get it to work. I ended up creating a non generic interface and assigning to the base class. Then use that to define all the types. Here is what I did:this.For<IMapperBase>().Use<CategoryMapper>().Named("CategoryMapper");Though what you have here seems way better and eliminates me having to add a new entry everytime a new mapper is created. I will definitely be giving this a try tonight to see if this will do what I need.
spinon