0

I'm trying to reduce duplicated code in an existing MVC 4 Web API 2 application. We are using AutoMapper to map the entities to custom DataObjects. We have an existing database that has multiple tables for 'Tags' pertaining to specific products (let's say bicycle, couch, and table).

I have a generic controller:

public class TagController<TTagDataObject> : ApiController where TTagDataObject : ITagDataObject
{
    private readonly ITagService<TTagDataObject> _service;

    public TagController(ITagService<TTagDataObject> service)
    {
        _service = service;
    }

    [HttpPost]
    public HttpResponseMessage Post(TTagDataObject model)
    {
        if (!ModelState.IsValid)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ModelState);
        }
        
        // Make service call
        model = _service.CreateTag(model);

        return Request.CreateResponse(HttpStatusCode.Created, model);
    }
... Other Methods
}

The application is using the Repository Pattern, and I'm having trouble creating the service because I need to define the Repository by entity type, and I only know the DataObject type. I can get the Entity type using AutoMapper's GetAllTypeMaps()

System.Type t = Mapper.GetAllTypeMaps().FirstOrDefault(i=> i.SourceType == typeof(TTagDataObject)).DestinationType;

How do I define and use the repository? I'd like to do something like:

Repository<t> repository = new Repository<t>();

But I get "The type or namespace 't' could not be found..."

I can define the repository using the Activator CreateInstance method as in this question: Pass An Instantiated System.Type as a Type Parameter for a Generic Class

var repository = Activator.CreateInstance(t);

But then unless I use reflection or dynamics I can't access the repository methods. It seems like there should be a much simpler solution to this, and am open to the possibility that I'm going about this the wrong way.

Thank you very much.

Community
  • 1
  • 1
Noel
  • 600
  • 16
  • 37
  • You should seriously consider ditching all these generics, services, repositories and the like. Check out my sample project here that uses EF, AutoMapper and IoC: https://github.com/jbogard/ContosoUniversity/blob/master/src/ContosoUniversity/Features/Instructor/UiController.cs – Jimmy Bogard Jun 02 '15 at 12:39
  • @JimmyBogard I would LOVE to drop a few layers out of this application, but we're stuck with service and repository pieces, even though they don't seem to add anything to the current application. – Noel Jun 02 '15 at 17:39
  • Does [this](http://stackoverflow.com/a/19201874/43846) help? – stuartd Jun 03 '15 at 16:56
  • @stuartd - Thank you. That makes me want to rethink the approach away from generics. It still seems like there should be some sort of way to define the repository based on the DestinationType returned by the mapper, but perhaps not.. – Noel Jun 03 '15 at 19:09

0 Answers0