的WebAPI与NinjectWebAPI、Ninject

2023-09-07 14:26:05 作者:綄镁の爱

我有一个麻烦,使得Ninject和WebAPI.All一起工作。我会更具体: 首先,我研究了一下WebApi.All包,看起来像它工作正常我。 第二,我加入的RegisterRoutes 的Global.asax 下一行:

I'm having a trouble, making Ninject and WebAPI.All working together. I'll be more specific: First, I played around with WebApi.All package and looks like it works fine to me. Second, I added to RegisterRoutes in Global.asax next line:

routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));

所以,最终的结果是:

So the final result was:


public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

        }

一切似乎是美好的,但是当我试图重定向用户到一个特定的动作,是这样的:

Everything seems to be fine, but when I'm trying to redirect user to a specific action, something like:

return RedirectToAction("Index", "Home");

网址在浏览器是本地主机:789 / API /触点动作=指数和放大器;控制器=首页  这是不好的。我swaped在 RegisterRoute 线,现在看起来:

Url in browser is localhost:789/api/contacts?action=Index&controller=Home Which is not good. I swaped lines in RegisterRoute and now it looks:


public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
            routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));
            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

        }

现在重定向工作正常,但是当我试图进入我的API的行为,我得到错误告诉我, Ninject不能回控制器API这是绝对合理的,我没有这样的控制器。 我做了搜索一些信息如何使Ninject工作,的WebAPI,但一切我发现仅是为MVC4或.Net 4.5。由技术问题我无法将项目移动到一个新的平台,所以我需要找到这个版本的一个可行的解决方案。  This回答看起来像一个工作的解决方案,但是当我试图启动项目,我在排队编译器错误

Now the redirection works fine, but when I try to access to my API actions, I get error telling me that Ninject couldn't return controller "api" which is absolutely logical, I don't have such controller. I did search some info how to make Ninject work with WebApi, but everything I found was only for MVC4 or .Net 4.5. By the technical issues I can't move my project to a new platform, so I need to find a working solution for this versions. This answer looked like a working solution, but when I'm trying to launch project I get compiler error in line

CreateInstance = (serviceType, context, request) => kernel.Get(serviceType);

告诉我: System.Net.Http.Htt prequestMessage在未引用的程序集定义 和一些有关的组装加REFFERENCE System.Net.Http,版本= 2.0.0.0,文化=中性公钥= 31bf3856ad364e35  我不知道下一步该怎么做,我找不到有关使用的WebAPI ninject在.NET 4和MVC3任何有用的信息。任何帮助将是AP preciated。

telling me: System.Net.Http.HttpRequestMessage is defined in an assembly that is not referenced and something about adding refference in assembly System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 I have no Idea what to do next, I couldn't find any useful info about ninject with webapi on .NET 4 and MVC3. Any help would be appreciated.

推荐答案

下面是几个步骤,我编的,你应该让你开始:

Here are a couple of steps I have compiled for you that should get you started:

创建使用互联网模板一个新的ASP.NET MVC 3项目 安装下列2 NuGets: Microsoft.AspNet.WebApi Ninject.MVC3

定义一个接口: Create a new ASP.NET MVC 3 project using the Internet Template Install the following 2 NuGets: Microsoft.AspNet.WebApi and Ninject.MVC3

Define an interface:

public interface IRepository
{
    string GetData();
}

和实施

.NET6 Asp.Net Core webapi 从零开始的webapi项目

And an implementation:

public class InMemoryRepository : IRepository
{
    public string GetData()
    {
        return "this is the data";
    }
}

添加一个API控制器:

Add an API controller:

public class ValuesController : ApiController
{
    private readonly IRepository _repo;
    public ValuesController(IRepository repo)
    {
        _repo = repo;
    }

    public string Get()
    {
        return _repo.GetData();
    }
}

注册一个API路线在的Application_Start

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    GlobalConfiguration.Configuration.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

添加使用Ninject自定义的Web API的依赖解析器:

Add a custom Web API Dependency Resolver using Ninject:

public class LocalNinjectDependencyResolver : System.Web.Http.Dependencies.IDependencyResolver
{
    private readonly IKernel _kernel;

    public LocalNinjectDependencyResolver(IKernel kernel)
    {
        _kernel = kernel;
    }

    public System.Web.Http.Dependencies.IDependencyScope BeginScope()
    {
        return this;
    }

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

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _kernel.GetAll(serviceType);
        }
        catch (Exception)
        {
            return new List<object>();
        }
    }

    public void Dispose()
    {
    }
}

注册内自定义依赖解析器的创建办法(〜/ App_Start / NinjectWebCommon.cs

Register the custom dependency resolver inside the Create method (~/App_Start/NinjectWebCommon.cs):

/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
    kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

    RegisterServices(kernel);

    GlobalConfiguration.Configuration.DependencyResolver = new LocalNinjectDependencyResolver(kernel); 
    return kernel;
}

配置 RegisterServices 法里面的内核(〜/ App_Start / NinjectWebCommon.cs ):

Configure the kernel inside the RegisterServices method (~/App_Start/NinjectWebCommon.cs):

/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IRepository>().To<InMemoryRepository>();
}        

运行应用程序并导航到 / API /值