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.