开发者

How to have structuremap build instance based on type

开发者 https://www.devze.com 2023-01-16 07:23 出处:网络
Ok so this 开发者_StackOverflowmight not be the best title but I am struggling with how to title this. Here is what I have thus far:

Ok so this 开发者_StackOverflowmight 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.


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>();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号