不能构造String类型.您必须配置容器以提供此值

本文关键字:配置 String 类型 不能 | 更新日期: 2023-09-27 18:14:30

我看了几个教程和stackoverflow问题如何实现统一的MVC 5项目,但我似乎无法通过这个错误:

不能构造String类型。您必须配置容器以提供此值。

我安装了NuGet包Unity。Mvc5,并在unity配置中注册了我的类型。我还在unityconfig文件中调用了register components方法。

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();
        // register all your components with the container here
        // it is NOT necessary to register your controllers
        // e.g. container.RegisterType<ITestService, TestService>();
        container.RegisterType<IStateService, StateService>();
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }
}
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    UnityConfig.RegisterComponents();
}
public class StateController : Controller
{
    private readonly IStateService stateService;
    public StateController(IStateService stateService)
    {
        this.stateService = stateService;
    }
    // GET: /State/
    public ActionResult Index()
    {
        return View(stateService.GetStates());
    }
}
public interface IStateService : IDisposable
{
    IEnumerable<State> GetStates();
}
public class StateService : IStateService
{
    private MyAppDbContext context;
    public StateService() : this(new MyAppDbContext()){}
    public StateService(MyAppDbContext context)
    {
        this.context = context;
    }
    private IQueryable<State> All()
    {
        return context.States;
    }
    public IEnumerable<State> GetStates()
    {
        return this.All().ToList();           
    }
    public void Dispose()
    {
        context.Dispose();
    }
}

下面是堆栈跟踪:


[InvalidOperationException: The type String cannot be constructed. You must configure the container to supply this value.]
   Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.GuardTypeIsNonPrimitive(IBuilderContext context) +311
   Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context) +229
   Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
   Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlanCreatorPolicy.CreatePlan(IBuilderContext context, NamedTypeBuildKey buildKey) +162
   Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +245
   Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
   Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +250
   Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
   lambda_method(Closure , IBuilderContext ) +215
   Microsoft.Practices.ObjectBuilder2.c__DisplayClass1.b__0(IBuilderContext context) +71
   Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
   Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +333
   Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
   Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +250
   Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
   lambda_method(Closure , IBuilderContext ) +205
   Microsoft.Practices.ObjectBuilder2.c__DisplayClass1.b__0(IBuilderContext context) +71
   Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
   Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +333
   Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
   Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +250
   Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
   lambda_method(Closure , IBuilderContext ) +209
   Microsoft.Practices.ObjectBuilder2.c__DisplayClass1.b__0(IBuilderContext context) +71
   Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
   Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +333
   Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
   Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +383
[ResolutionFailedException: Resolution of the dependency failed, type = "MyApp.MVC.Controllers.StateController", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type String cannot be constructed. You must configure the container to supply this value.
-----------------------------------------------
At the time of the exception, the container was:
  Resolving MyApp.MVC.Controllers.StateController,(none)
  Resolving parameter "stateService" of constructor MyApp.MVC.Controllers.StateController(MyApp.Service.Services.IStateService stateService)
    Resolving MyApp.Service.Services.StateService,(none) (mapped from MyApp.Service.Services.IStateService, (none))
    Resolving parameter "context" of constructor MyApp.Service.Services.StateService(MyApp.Data.DAL.MyAppDbContext context)
      Resolving MyApp.Data.DAL.MyAppDbContext,(none)
      Resolving parameter "connectionString" of constructor MyApp.Data.DAL.MyAppDbContext(System.String connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model)
        Resolving System.String,(none)
]
   Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +446
   Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides) +50
   Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides) +48
   Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides) +61
   Unity.Mvc5.UnityDependencyResolver.GetService(Type serviceType) +140
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +87
[InvalidOperationException: An error occurred when trying to create a controller of type 'MyApp.MVC.Controllers.StateController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +247
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +438
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +257
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +326
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +157
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

我可能做错了什么?

我在UnityConfig类中添加了以下代码到RegisterComponents方法,它似乎正在工作:

container.RegisterInstance<StateService>(new StateService());

没有教程显示需要这样做,我觉得我的例子用得很标准。为什么我需要这一行?我还不太了解Unity,所以这就是为什么我仍然很好奇。

不能构造String类型.您必须配置容器以提供此值

我没有在任何地方看到这个答案,所以我也想添加这个。在我看来,你在你的StateService对象上有多个构造函数。所以,Unity会选择具有最多参数的构造函数(正如在评论中提到的)。

你调用InjectionConstructor告诉Unity使用哪个构造函数。

下面告诉它使用无参数构造函数。

container.RegisterType<IStateService, StateService>(new InjectionConstructor());

或者你也可以告诉它使用一个带类型的。

container.RegisterType<IStateService, StateService>(new InjectionConstructor(<some type>))

这将强制Unity使用你想要的构造函数

您的服务正在尝试解析"context"。我建议你不要让你的上下文出现在DI映射中,所以不要让它出现在你想要解析的构造函数中。

Resolving parameter "context" of constructor MyApp.Service.Services.StateService(MyApp.Data.DAL.MyAppDbContext context)