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();
}}
这是我的错误堆栈. 没有为此对象定义的无参数构造函数.
有人可以帮我吗 谢谢. 解决方法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 (编辑:哈尔滨站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net-mvc – 在Asp.Net MVC中使用千位分隔符的十进制值
- asp.net-mvc – 在Controller操作方法中重用代码的最佳方法
- asp.net+Ajax 文本文件静态分页实现代码
- asp.net – 增加IIS7 / Win7 Pro上的最大上传文件大小
- asp.net-mvc-3 – 在MVC Razor View中使用If语句
- asp.net-mvc – 通过Gitignore递归地包含Nuget DLL
- asp.net-mvc – MVC DB首先修复显示名称
- ASP.NET和System.Diagnostics跟踪 – 我错过了什么,或者这是
- asp.net-mvc – Url.Action生成查询字符串,以任何方式生成完
- asp.net-mvc – asp.net mvc 4从控制器按钮调用方法
- asp.net-mvc-3 – RedirectResult Object作为URL
- asp.net – compilation debug =“true”和发布模
- asp.net – “2015年4月20日Google帐户的OpenID2
- asp.net – 我应该在.gitingore文件中包含.vs文件
- asp.net-mvc-3 – MVC3剃须刀:是否可以渲染传统
- asp.net-mvc – 从MVC版本1迁移后,ASP.NET MVC 2
- js触发asp.net的Button的Onclick事件应用
- asp.net(C#)禁止缓存文件不让文件缓存到客户端
- asp.net-mvc-3 – Azure网站上的RavenDb – 访问
- asp.net – Javascript日期本地化
