c# - 依赖注入(inject)不适用于 Owin 自托管 Web Api 2 和 Autofac

标签 c# autofac owin asp.net-web-api2

我正在学习 Web Api 2、Owin 和 Autofac,需要一些指导。

概览
我有一个 Owin 自托管 Web Api,它使用 Autofac 进行 IoC 和依赖项注入(inject)。该项目是一个类似于服务的控制台应用程序,这意味着它可以停止和启动。我有一个带有两个构造函数的身份验证 Controller :一个无参数,另一个注入(inject)存储库。

问题
当我运行服务并调用 api 时,我的无参数构造函数被调用并且我的存储库永远不会被注入(inject) (_repository = null)。

研究
我做了相当多的研究,并在 Github 上找到了一些有用的项目,我将它们复制到了 T 恤上,但我遗漏了很大一部分难题。 This很有帮助,但没有解决我的问题。我读了this question在 Stack Overflow 和 Dane Sparza 上有一个很好的 demo project但我找不到明确的解决方案。问题不在于自托管,而在于依赖注入(inject)。

我的代码(为了解释而精简)

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

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

        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        var connectioninfo = ConnectionInfo.FromAppConfig("mongodb");

        var builder = new ContainerBuilder();                                    // Create the container builder.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());         // Register the Web API controllers.
        builder.Register(c => new Logger()).As<ILogger>().InstancePerRequest();  // Register a logger service to be used by the controller and middleware.
        builder.RegisterType<AuthenticationRepository>().As<IAuthenticationRepository>().WithParameter(new NamedParameter("connectionInfo", connectioninfo)).InstancePerRequest();

        var container = builder.Build();

        var resolver = new AutofacWebApiDependencyResolver(container);           // Create an assign a dependency resolver for Web API to use.
        GlobalConfiguration.Configuration.DependencyResolver = resolver;         // Configure Web API with the dependency resolver

        app.UseCors(CorsOptions.AllowAll);  
        app.UseWebApi(config);
        app.UseAutofacWebApi(config);  // Make sure the Autofac lifetime scope is passed to Web API.
    }

程序.cs

 static void Main(string[] args)
    {           
        var service = new ApiService(typeof(Program), args);

        var baseAddress = "http://localhost:9000/";
        IDisposable _server = null;

        service.Run(
           delegate()
           {
               _server = WebApp.Start<Startup>(url: baseAddress);
           },
           delegate()
           {
               if (_server != null)
               {
                   _server.Dispose();
               }
           }
       );
    }

API Controller

public class AuthenticationController : ApiController
{
    private IAuthenticationRepository _repository;

    public AuthenticationController() { }

    public AuthenticationController(IAuthenticationRepository repository)
    {
        _repository = repository;
    }

    [AllowAnonymous]
    public IHttpActionResult Authenticate(string name, string password)
    {
        if (_repository == null)
            return BadRequest("User repository is null.");

        var valid = _repository.AuthenticateUser(name, password);
        return Ok(valid);
    }
}

最佳答案

您应该使用 HttpConfiguration 来在任何地方引导 OWIN。 所以,这:

GlobalConfiguration.Configuration.DependencyResolver = resolver;

应该变成:

config.DependencyResolver = resolver;

除此之外,一切看起来都很好。 Api Controller 已注册,尽管您没有给它们一个范围。不确定 Autofac 范围是否默认为 Controller 的每个请求,或者它是否具有每个请求范围的概念(我知道 LightInject 有它)。

环顾四周,我认为您遵循了 Autofac 的 Google 代码存储库中的示例,它确实使用了 GlobalConfiguration。相反,如果您查看 GitHub example ,有点不一样。尝试根据此进行更改。包括这个:

// This should be the first middleware added to the IAppBuilder.
app.UseAutofacMiddleware(container);

2016 年更新

我上面所说的仍然适用,但来自 Autofac 文档的额外内容(感谢 Brad):

A common error in OWIN integration is use of the GlobalConfiguration.Configuration. In OWIN you create the configuration from scratch. You should not reference GlobalConfiguration.Configuration anywhere when using the OWIN integration.

关于c# - 依赖注入(inject)不适用于 Owin 自托管 Web Api 2 和 Autofac,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25177734/

相关文章:

c# - Asp.net Core AutoFac 使用工厂注册泛型

autofac - 仅给出字符串键是否可以从 Autofac 解析实例?

signalr - 无法使用 OWIN Self Host 关闭并启动新的 SignalR

c# - 我似乎无法获得一个非常基本的 cookie 登录示例来使用 MVC5 和 OWIN

oauth-2.0 - OpenIdConnectAuthenticationOptions 和 AcquireTokenByAuthorizationCodeAsync : Invalid JWT token

c# - 机器人仿真器框架无法解析服务

c# - ASP.NET 核心 Web API : Required parameter with conditions

c# - 在 C# 中处理字符串化的 JS 对象

c# - NPOI中如何枚举excel工作表

ioc-container - AutoFac - 使用已知服务实例化未注册的服务