Не удается зарегистрировать контроллер API с помощью Simple Injector?

У меня есть WebApi, использующий Simple Injector, который отлично работал, но мне пришлось внедрить OAuth в проект. Теперь я сделал это, и мои ApiControllers выдают мне ошибку, например, Simple Injector теперь настроен правильно.

У меня есть файл Start.cs

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // Web API configuration and services
        HttpConfiguration config = new HttpConfiguration();

        Container container = SimpleInjectorConfig.Initialize(app);

        ConfigureAuth(app, container);

        WebApiConfig.Register(config);

        app.UseWebApi(config);
    }

    public void ConfigureAuth(IAppBuilder app, Container container)
    {
        var OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = container.GetInstance<IOAuthAuthorizationServerProvider>()
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

    }
}

В моем файле SimpleInjectorConfig у меня есть

public class SimpleInjectorConfig
{
    public static Container Initialize(IAppBuilder app)
    {
        var container = GetInitializeContainer(app);

        container.Verify();

        GlobalConfiguration.Configuration.DependencyResolver = 
            new SimpleInjectorWebApiDependencyResolver(container);

        return container;
    }

    public static Container GetInitializeContainer(IAppBuilder app)
    {
        var container = new Container();

        container.RegisterSingle<IAppBuilder>(app);

        container.Register<IOAuthAuthorizationServerProvider, 
            ApiAuthorizationServerProvider>();

        // myService
        container.Register<IService, MyService>();

        // myRepository
        container.Register<IRepository, MyRepository>();

        // This is an extension method from the integration package.
        container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

        return container;
    }
}

public class ApiAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    private IService _service;

    public ApiAuthorizationServerProvider(IService service)
    {
        _service = service;
    }

    public override async Task ValidateClientAuthentication(
        OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(
        OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers
            .Add("Access-Control-Allow-Origin", new[] { "*" });

        User user = _service.Query(e => e.Email.Equals(context.UserName) &&
            e.Password.Equals(context.Password)).FirstOrDefault();

        if (user == null)
        {
            context.SetError("invalid_grant", 
                "The user name or password is incorrect.");
            return;
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);

    }
}

Теперь мой проект строится нормально, но я не могу проверить, работает ли OAuth, потому что я не могу подключиться к своему ApiController. Я еще не добавил тег [Authorize] в контроллер, поэтому у меня должен быть доступ к нему.

Вот мой контроллер

public class MyController : ApiController
{
    private IService _service;

    public MyController(IService service)
    {
        _service = service;
    }

    public IHttpActionResult Get()
    {
        // get all entities here via service
        return Ok(list);
    }

}

Сообщение об ошибке, которое я получаю, говорит

Произошла ошибка при попытке создать контроллер типа MyController. Убедитесь, что у контроллера есть публичный конструктор без параметров.

Я думал, что это будет зарегистрировано через

container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

person Gillardo    schedule 23.09.2014    source источник
comment
Привет, если вы удалите материал OAuth, вы можете в ApiController?   -  person Spock    schedule 24.09.2014
comment
Установка GlobalConfiguration.Configuration.DependencyResolver и вызов RegisterWebApiControllers обычно помогают. Можете ли вы опубликовать полную трассировку стека?   -  person Steven    schedule 24.09.2014
comment
У меня такие же настройки и такая же проблема. Вот трассировка стека, которую я получил: в System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create (запрос HttpRequestMessage, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n в System.Web.Http.Controllers.HttpControllerDescriptor.CreateController (запрос HttpRequestMessage)\ r\n в System.Web.Http.Dispatcher.HttpControllerDispatcher.‹SendAsync›d__1.MoveNext()   -  person von v.    schedule 29.01.2015
comment
@Steven, вот трассировка стека во внутреннем исключении: в System.Linq.Expressions.Expression.New(Type type)\r\n в System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\ n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(запрос HttpRequestMessage, Type controllerType, Func`1& activator)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType )   -  person von v.    schedule 29.01.2015
comment
@vonv. пожалуйста, опубликуйте новый вопрос с подробным описанием вашей проблемы, как воспроизвести и всеми соответствующими деталями ошибки (тип исключения, сообщение и трассировка стека исключения и все внутренние исключения).   -  person Steven    schedule 29.01.2015
comment
Похоже, что-то не создается или существует циклическая зависимость.   -  person Rickey    schedule 25.11.2019


Ответы (1)


В .NET Core добавьте:

// Sets up the basic configuration that for integrating Simple Injector with
// ASP.NET Core by setting the DefaultScopedLifestyle, and setting up auto
// cross wiring.
services.AddSimpleInjector(_container, options =>
{
    // AddAspNetCore() wraps web requests in a Simple Injector scope and
    // allows request-scoped framework services to be resolved.
    options.AddAspNetCore()
        .AddControllerActivation();
});

через https://simpleinjector.readthedocs.io/en/latest/aspnetintegration.html

person Saibamen    schedule 29.07.2020