尝试创建“ ProductsController”类型的控制器时发生错误。确保控制器具有无参数的公共构造函数

时间:2018-12-10 16:07:44

标签: asp.net-web-api structuremap4

无论何时调用端点,我都在使用StructureMap为AdevntureWork示例Web API Project 4.6.2注册服务。 http://localhost:xxx/api/v1/products/all  像下面这样抛出错误

  

  尝试创建“ ProductsController”类型的控制器时发生错误。确保控制器具有无参数的公共构造函数。    

     

System.InvalidOperationException      在System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15的System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage请求)的System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage请求,HttpControllerDescriptor controllerDescriptor,类型controllerType) .MoveNext()   

代码如下:

Startup.cs文件:

     public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
        var config = new HttpConfiguration();

        config.AddApiVersioning(opt => opt.AssumeDefaultVersionWhenUnspecified = true);

        var constraintResolver = new DefaultInlineConstraintResolver()
        {
            ConstraintMap =
            {
                ["apiVersion"] = typeof( ApiVersionRouteConstraint )
            }
        };
        config.MapHttpAttributeRoutes(constraintResolver);

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

        var container = new Container(x =>
        {
            x.AddRegistry<IoCRegistry>();
        });


        Mapper.Initialize(x =>
        {
            x.AddProfile<ProductProfile>();
        });



        config.DependencyResolver = new StructureMapWebApiDependencyResolver(container);

        config.Filters.Add(new ApiExceptionFilterAttribute());

        app.Use<ErrorHandlingMiddleware>(config.DependencyResolver.GetService(typeof(ILogger<ErrorHandlingMiddleware>)));
        config.EnableSwagger(c =>
        {
            c.SingleApiVersion("1", "AdventureWork.API");
            c.DescribeAllEnumsAsStrings();
            c.DocumentFilter<SwaggerRouteVersion>();
        })
        .EnableSwaggerUi();

        app.UseWebApi(config);
    }
}

IoCRegitry.cs文件看起来像

public class IoCRegistry : Registry
{
    public IoCRegistry()
    {
        Scan(_ =>
        {
            _.TheCallingAssembly();
            _.Assembly("AdventureWork.DTO");
            _.Assembly("AdventureWork.EFProvider");
            _.Assembly("AdventureWork.Objects");
            _.Assembly("AdventureWork.Repo");
            _.Assembly("AdventureWork.Manager");
            _.LookForRegistries();
            _.WithDefaultConventions();
        });

        AdventureWorkRepositoryDbContextOptions contextOptions = new AdventureWorkRepositoryDbContextOptions(ConfigurationManager.AppSettings["DBConnectionString"].ToString());

        For<IAdventureWorkRepositoryDbContextOptions>().Singleton().Use(contextOptions);
        For<AdventureWorkRepositoryDbContextOptions>().Singleton().Use(contextOptions);
        For<IDbContextFactory<AdventureWorkRepositoryDbContext>>().Use<AdventureWorkRepositoryDbContextFactory>();
        For<IProductManager>().Use<ProductManager>();

        For<IRepository<Product>>().Singleton().Use<Repository<Product>>();

        For<IMyDbContext>().Singleton()
        .Use<MyDbContext>().Ctor<string>("connectionString").Is(ConfigurationManager.AppSettings["DBConnectionString"].ToString());

    }
}

ProductsController.cs文件:

 [RoutePrefix("api/v{version:apiVersion}/products")]
public class ProductsController : ApiController
{
    private readonly IProductManager _manager;
    private readonly ILogger<ProductsController> logger;

    public ProductsController(IProductManager manager,ILogger<ProductsController> logger)
    {
        _manager = manager;
        this.logger = logger;
    }

    // GET api/<controller>
    [HttpGet, Route("all")]
    public async Task<IEnumerable<Product>> Get()
    {
        var products = await _manager.GetProducts();
        return products;

    } 
}

服务注册表中似乎有一个我无法识别的错误,任何人都可以帮助我找到它。

**还值得一提的是,结构图DI在具有相同存储库的.NET Core 2.1项目上工作,但是在使用DBContextFactory遇到另一个错误时,我在另一个问题中发布了该信息。

0 个答案:

没有答案