【问题标题】:An error occurred when trying to create a controller of type 'SaleController'. Make sure that the controller has a parameterless public constructor尝试创建类型为“SaleController”的控制器时发生错误。确保控制器有一个无参数的公共构造函数
【发布时间】:2019-10-20 18:29:01
【问题描述】:

我一直在关注这篇文章:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection#dependency-scope-and-controller-lifetime

我得到的错误在标题中:

确保控制器有一个无参数的公共构造函数。

Unity 代码基本上与 microsoft 项目中的相同。

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var container = new UnityContainer();

        container.RegisterType<ITrace, Trace>(new HierarchicalLifetimeManager());
        container.RegisterType<IUtility, Utility>(new HierarchicalLifetimeManager());
        container.RegisterType<IValidator, Validator>(new HierarchicalLifetimeManager());
        container.RegisterType<IDeliveryService, DeliveryService>(new HierarchicalLifetimeManager());
        container.RegisterType<ISaleService, SaleService>(new HierarchicalLifetimeManager());
        config.DependencyResolver = new UnityResolver(container);


        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

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

我有 UnityResolver:

public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer container;

    public UnityResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        this.container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose()
    {
        container.Dispose();
    }

Unity 应该使用它来实例化控制器。我唯一关心的是数据库上下文。我尝试寻找注册方式,但一无所获。

这里问的是我的 dbcontext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false)
    {
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
        Configuration.ValidateOnSaveEnabled = false;
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

我是第一次使用 Unity。

【问题讨论】:

  • 能分享下DbContext的相关代码吗?
  • 我已经用数据库上下文更新了问题。
  • 我发现如果我将依赖范围注册为 TransientLifetimeManager ,程序正在进入控制器但返回空引用异常。

标签: c# unity3d


【解决方案1】:

在 Unity 中,有时具有特定构造函数的自定义类还需要额外的无参数构造函数(它可能什么都不做,但必须存在),例如

public UnityResolver(){ }

Afaik 这主要与(反)序列化有关。不知道为什么在我们的特定情况下需要它..但这就是错误试图告诉你的;)

【讨论】:

  • 每一堂课都这样吗?
  • 不总是... afaik它基本上与序列化有关,因此每次以任何方式(反)序列化类时都需要默认构造函数。但是我不确定为什么在您的特定情况下需要它...但这就是错误要告诉您的内容;)
  • 我尝试将无参数参数放在构造函数上,但无济于事。
  • 截止日期快到了,但仍然没有关于如何解决这个问题的信息......
  • 所以将public UnityResolver(){ } 添加到您的UnityResolver 类并没有改变任何东西?
猜你喜欢
  • 2022-11-04
  • 2019-04-13
  • 2017-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多