I have a controller that looks something like this:
public class MyController : MyController
{
private readonly IMyService service;
public MyController(IMyService _service)
{
service = _service;
}
[HttpGet]
public BaseFoo GetFoo(Guid id)
{
return service.GetFoo(id);
}
}
Ninject will inject IMyService for me. Now in my implementation of IMyService, I would like to be able to create objects derived from BaseFoo. So I originally had something like this:
public MyService : IMyService
{
public BaseFoo GetFoo(Guid id)
{
Type t = // some code that determines which type we actually need
return (BaseFoo) Activator.CreateInstance(t);
}
}
Which worked fine. But now what I'd like to do is have different implementations of BaseFoo be dependent on different services (or no services). So for example, I might have:
public SomeFoo : BaseFoo
{
public SomeFoo(IOtherService _service)
{
}
}
And, ideally, I'd like to have Ninject handle that dependency injection, but I'm not sure what the right way to handle this is. MyService needs to handle creating BaseFoo objects, so I thought add a constructor like this:
public MyService(IKernel kernel)
Which gets the kernel injected and then in GetFoo instead of using Activator I can:
return (BaseFoo) kernel.Get(t);
This works. But doesn't feel right. It requires MyService to know about Ninject and that seems wrong.
Is there a better pattern to use here?
Edit: BatteryBackupUnit suggests using the ninject factory extension, which sounds like that's probably a better solution, but I don't quite see how to make it work in this case. If I create a IFooFactory, I would imagine it would need to look like this:
public interface IFooFactory
{
BaseFoo CreateFoo(Type t);
}
But this will try to create an instance of BaseFoo passing in a type to the constructor, which isn't what I need. BaseFoo is abstract, I need a factory that will create a concrete instance of type t that is derived from BaseFoo.