1
votes

I'm converting a project from WCF Web API to ASP.NET Web API - thanks MS :(

Self Hosting POC code:

    static void Main(string[] args)
    {
        var kernel = new StandardKernel();

        const string baseAddress = "http://localhost:8080";
        var config = new HttpSelfHostConfiguration(baseAddress);
        config.ServiceResolver.SetResolver(new NinjectServiceLocator(kernel));

        config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional});

        var server = new HttpSelfHostServer(config);
        server.OpenAsync().Wait();
        Console.WriteLine("The server is running....");
        Console.ReadLine();
    }

I'm registering Ninject as the dependency resolver. To accomplish this, I am using the CommonServiceLocator.NinjectAdapter to register it:

config.ServiceResolver.SetResolver(new NinjectServiceLocator(kernel));

This seems to work as far as I can tell although it feels a little dirty using SetResolver(object).

The problem I have now is when I try to run it there are a lot of bindings that are no longer registered (i.e. IHttpContollerFactory, ILogger, etc.).

Do I have to go through one-by-one and re-register all of the "default" dependencies? It seems odd that defaults are registered with the default dependency resolver but I can't see a quick way to re-register the defaults when a new dependency resolver is set. For something like the ILogger, I can't even seem to gain access to the default System.Web.Http.Common.Logging.DiagnosticLogger to make the binding.

Am I missing something?

2

2 Answers

2
votes

You don't have to re-register the default services. If you return null the framework will default back to it's internal DI container. Also, in the latest bits it will only ask once.

0
votes

In the end it is probably better just to create a IDependencyResolver for Ninject. I'm sure there will be a "proper" one created by someone whom has greater knowledge of Ninject but for now I'm using:

public class NinjectDependencyResolverAdapter : IDependencyResolver
{
    private readonly IKernel kernel; 

    public NinjectDependencyResolverAdapter(IKernel kernel)
    {
        this.kernel = kernel;
    }

    #region Implementation of IDependencyResolver

    public object GetService(Type serviceType)
    {
        return kernel.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return kernel.GetAll(serviceType);
    }

    #endregion
}