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 (编辑:日照站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- .net – 有人有一个例子,说明为什么我会主持一个WCF服务
- asp.net-mvc – 使用CORS在WebAPI中将text / plain作为复杂
- asp.net-mvc – 使用没有ORM的ASP.NET MVC
- ASP.NET MVC Url路由支持(点)
- 从ASP.NET应用程序使用Active Directory时,DirectoryServic
- asp.net – 未知的服务器标签’ajaxToolkit:CalendarExten
- asp.net Web.config 详细配置说明
- asp.net-mvc – 当我不知道内容类型时如何返回文件结果
- asp.net – 检查IE浏览器 – .NET
- MVC学习二:基础语法
- asp.net-mvc – ASP.NET MVC应用程序的WatiN最佳
- asp.net – 如何设置显示内联的Div元素的固定宽度
- asp.net-mvc – 为什么MVC4捆绑捆绑Knockout.js?
- asp.net实现生成缩略图及给原始图加水印的方法示
- asp.net – 干净的方式来防止输入按钮提交表单
- asp.net-mvc – 在一个页面中以两种不同的形式使
- ASP.NET网站管理系统退出 清除浏览器缓存,Sessio
- asp.net-mvc – ASP.NET MVC运行IIS7部署问题
- asp.net-mvc – 如何将XML作为POST传递给ASP MVC
- asp.net – 在Web.config帮助中定义tagPrefixes
