asp.net-mvc-3 – 在使用Unity容器时为此对象异常定义的无参数构造函数

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 在使用Unity容器时为此对象异常定义的无参数构造函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我得到上述异常,而trynig加载视图.

我正在使用Unity来初始化我的控制器实例.仍然得到上述错误.

这是我的控制器.

public class SiteController : Controller
{

    private ISiteRepository _repository;

    public SiteController(ISiteRepository repository)
    {
        _repository = repository;
    }

    //
    // GET: /Site/

    public ActionResult Index()
    {
        return View();
    }

    //
    // GET: /Site/Details/5

    public ActionResult Details(int id)
    {
        return View();
    }}

这里是我的Global.asax.cs

protected void Application_Start()
    {
        ConfigApi(GlobalConfiguration.Configuration);
        AreaRegistration.RegisterAllAreas();

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

    static void ConfigApi(HttpConfiguration config)
    {
        var unity = new UnityContainer();
        unity.RegisterType<SiteController>();
        unity.RegisterType<ISiteRepository,SiteRepository>(new HierarchicalLifetimeManager());

        config.DependencyResolver = new IocContainer(unity);
    }

这是我的SiteRepository类.

public class SiteRepository:ISiteRepository
{
    private readonly SampleMVCEntities _dbContext;

    public SiteRepository()
    {
        _dbContext = new SampleMVCEntities();
    }

    private IQueryable<SiteConfig> MapSiteConfig()
    {
        return _dbContext.SiteConfigs.Select(a => new SiteConfig
        {
            Name = a.Name,LinkColour = a.LinkColour,Sitelogo = a.Sitelogo,SiteBrands = a.SiteBrands.Select(b => new Models.SiteBrand { SiteId = b.SiteId,BrandId = b.BrandId })
        });
    }

    public IEnumerable<SiteConfig> GetAll()
    {
        return MapSiteConfig().AsEnumerable();
    }}

这是我的错误堆栈.

没有为此对象定义的无参数构造函数.
说明:在执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪以获取有关错误的更多信息及其在代码中的位置.

Exception Details: System.MissingMethodException: No parameterless
constructor defined for this object.

Source Error:

An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.

Stack Trace:

[MissingMethodException: No parameterless constructor defined for this
object.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type,
Boolean publicOnly,Boolean noCheck,Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor,Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly,Boolean
skipCheckThis,Boolean fillCache,StackCrawlMark& stackMark) +114
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
Boolean skipCheckThis,StackCrawlMark& stackMark)
+232 System.Activator.CreateInstance(Type type,Boolean nonPublic) +83 System.Activator.CreateInstance(Type type) +6 System.Web.Mvc.DefaultControllerActivator.Create(RequestContext
requestContext,Type controllerType) +55

[InvalidOperationException: An error occurred when trying to create a
controller of type ‘Config.Controllers.SiteController’. Make sure that
the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext
requestContext,Type controllerType) +179
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext
requestContext,Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext
requestContext,String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase
httpContext,IController& controller,IControllerFactory& factory)
+197 System.Web.Mvc.<>c_DisplayClass6.b_2() +49 System.Web.Mvc.<>c__DisplayClassb1.<ProcessInApplicationTrust>b__a()
+13 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action
action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func
1 func) +88
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase
httpContext,AsyncCallback callback,Object state) +98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,
AsyncCallback callback,Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext
context,AsyncCallback cb,Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+268 System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean& completedSynchronously) +155

有人可以帮我吗

谢谢.

解决方法

ASP.NET MVC和ASP.NET Web API使用两个独立的依赖解析器.

对于从Controller得到的“常规”MVC控制器,您需要使用DependencyResolver.SetResolver:

DependencyResolver.SetResolver(new UnityDependencyResolver(container));

对于由ApiController派生的Wep API控制器,您需要像代码中一样使用GlobalConfiguration.Configuration.DependencyResolver.

所以如果你打算使用这两种类型的控制器,你需要注册你的容器两次.

有一个很好的文章如何为依赖解析器设置Unity:

Dependency Injection in ASP.NET MVC 4 and WebAPI using Unity

原文链接:https://www.f2er.com/aspnet/245828.html

猜你在找的asp.Net相关文章