接口,无法在Unity配置上构建

2024-01-31

我在这个项目上使用 Unity 时遇到问题。

错误是

当前类型 Business.Interfaces.IPersonnelBusiness 是 接口,无法构造。您是否缺少类型映射?

由于堆栈溢出,我已将 Unity 更新到最新版本issue https://github.com/unitycontainer/unity/issues/158我看到 RegisterComponents 已更改为延迟加载 这是全局 asax:

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Unity settings
            //UnityConfig.RegisterComponents();

            // For logging
            //SetupSemanticLoggingApplicationBlock();
        }

这是 UnityConfig 文件:

public static class UnityConfig
    {
        #region Unity Container
        private static Lazy<IUnityContainer> container =
          new Lazy<IUnityContainer>(() =>
          {
              var container = new UnityContainer();
              RegisterTypes(container);
              return container;
          });

        /// <summary>
        /// Configured Unity Container.
        /// </summary>
        public static IUnityContainer Container
        {
            get
            {
                return container.Value;
            }
        }
        #endregion

        /// <summary>
        /// Registers the type mappings with the Unity container.
        /// </summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>
        /// There is no need to register concrete types such as controllers or
        /// API controllers (unless you want to change the defaults), as Unity
        /// allows resolving a concrete type even if it was not previously
        /// registered.
        /// </remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below.
            // Make sure to add a Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            // TODO: Register your type's mappings here.
            // container.RegisterType<IProductRepository, ProductRepository>();
            container = new UnityContainer();

            // Identity managment
            container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
            container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
            container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
            container.RegisterType<AccountController>(new InjectionConstructor());
            container.RegisterType<PersonnelController>(new InjectionConstructor());
            container.RegisterType<UsersAdminController>(new InjectionConstructor());

            // Business Layer
            container.RegisterType<ILogBusiness, LogBusiness>();
            container.RegisterType<IAnomalyBusiness, AnomalyBusiness>();
            container.RegisterType<ICockpitStatBusiness, CockpitStatsBusiness>();
            container.RegisterType<IDocumentBusiness, DocumentBusiness>();
            container.RegisterType<IEmailBusiness, EmailBusiness>();
            container.RegisterType<IMessageBusiness, MessageBusiness>();
            container.RegisterType<INatureBusiness, NatureBusiness>();
            container.RegisterType<IPersonnelBusiness, PersonnelBusiness>();
            container.RegisterType<ISAPBusiness, SAPBusiness>();

            // Set resolver
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

        }
    }

谢谢大家

EDIT:

这是堆栈和抛出它的代码:

堆栈跟踪:

[ResolutionFailedException: Resolution of the dependency failed, type = 'APPI.WEB.Controllers.HomeController', name = '(none)'.
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, APPI.Business.Interfaces.IPersonnelBusiness, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was: 
  Resolving APPI.WEB.Controllers.HomeController,(none)
  Resolving parameter 'personnelRepo' of constructor APPI.WEB.Controllers.HomeController(APPI.Business.Interfaces.IPersonnelBusiness personnelRepo, APPI.Business.Interfaces.IAnomalyBusiness anomalyRepo, APPI.Business.Interfaces.IDocumentBusiness docRepo, APPI.Business.Interfaces.IMessageBusiness msgRepo, APPI.Business.Interfaces.ICockpitStatBusiness cockpitStatRepo, APPI.Business.Interfaces.INatureBusiness natureRepo)
    Resolving APPI.Business.Interfaces.IPersonnelBusiness,(none)
]

控制器:

public class HomeController : BaseController
    {

        private readonly IPersonnelBusiness _IPersonnelBusinessRepo;
        private readonly IAnomalyBusiness _IAnomalyBusinessRepo;
        private readonly IDocumentBusiness _IDocumentBusinessRepo;
        private readonly IMessageBusiness _IMessageBusinessRepo;
        private readonly ICockpitStatBusiness _ICockpitStatBusinessRepo;
        private readonly INatureBusiness _INatureBusinessRepo;

        // Unity inject references
        public HomeController(IPersonnelBusiness personnelRepo, IAnomalyBusiness anomalyRepo, IDocumentBusiness docRepo, 
            IMessageBusiness msgRepo, ICockpitStatBusiness cockpitStatRepo, INatureBusiness natureRepo)
        {
            _IPersonnelBusinessRepo = personnelRepo;
            _IAnomalyBusinessRepo = anomalyRepo;
            _IDocumentBusinessRepo = docRepo;
            _IMessageBusinessRepo = msgRepo;
            _ICockpitStatBusinessRepo = cockpitStatRepo;
            _INatureBusinessRepo = natureRepo;
        }
        public HomeController()
        {

        }

        public ActionResult Index()
        {
            return RedirectToActionPermanent("Cockpit", "Home");
        }

还有在启动应用程序之前调用的 UnityActivator,这要归功于

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(APPI.WEB.UnityMvcActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(APPI.WEB.UnityMvcActivator), "Shutdown")]

统一激活器:

public static class UnityMvcActivator
{
    /// <summary>
    /// Integrates Unity when the application starts.
    /// </summary>
    public static void Start() 
    {
        FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
        FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(UnityConfig.Container));

        DependencyResolver.SetResolver(new UnityDependencyResolver(UnityConfig.Container));

        // TODO: Uncomment if you want to use PerRequestLifetimeManager
        // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
    }

    /// <summary>
    /// Disposes the Unity container when the application is shut down.
    /// </summary>
    public static void Shutdown()
    {
        UnityConfig.Container.Dispose();
    }
}

正如评论中指出的,问题是您在初始化程序中实例化了 2 个不同的容器:

    private static Lazy<IUnityContainer> container =
      new Lazy<IUnityContainer>(() =>
      {
          var container = new UnityContainer(); // <-- new container here
          RegisterTypes(container);
          return container;
      });

一旦进入你的RegisterTypes method:

    public static void RegisterTypes(IUnityContainer container)
    {
        // NOTE: To load from web.config uncomment the line below.
        // Make sure to add a Unity.Configuration to the using statements.
        // container.LoadConfiguration();

        // TODO: Register your type's mappings here.
        // container.RegisterType<IProductRepository, ProductRepository>();
        container = new UnityContainer(); // <-- new container here

    ...

类型映射被添加到RegisterTypes方法到一个不同的实例比您作为参数传递的容器。

为了使其正常工作,您应该删除容器的实例化RegisterTypes因此它可以使用参数中传递的实例。

    public static void RegisterTypes(IUnityContainer container)
    {
        // NOTE: To load from web.config uncomment the line below.
        // Make sure to add a Unity.Configuration to the using statements.
        // container.LoadConfiguration();

        // TODO: Register your type's mappings here.
        // container.RegisterType<IProductRepository, ProductRepository>();
        // container = new UnityContainer(); // <-- Remove this

    ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

接口,无法在Unity配置上构建 的相关文章

  • 为什么我不能用 `= delete;` 声明纯虚函数?

    Intro 纯虚函数使用通用语法声明 virtual f 0 然而 自 c 11 以来 有一种方法可以显式地传达non existence 特殊 成员函数的 Mystruct delete eg default constructor Q
  • 我的 Razor 视图中出现奇怪的自动命名空间导入

    今天我注意到 例如 System 和 System Web Security 已导入到我的所有 razor 视图中 尽管我没有主动导入它们 我检查了 using指令 web config 编辑 也是全局 web config 添加全局导入
  • 为什么要序列化对象需要 Serialized 属性

    根据我的理解 SerializedAttribute 不提供编译时检查 因为它都是在运行时完成的 如果是这样 那么为什么需要将类标记为可序列化呢 难道序列化器不能尝试序列化一个对象然后失败吗 这不就是它现在所做的吗 当某些东西被标记时 它会
  • 对齐 GridView 中的行值

    我需要在 asp net 3 5 中右对齐 gridview 列中的值 我怎样才能做到这一点
  • 如何从 C# 控制器重定向到外部 url

    我使用 C 控制器作为网络服务 在其中我想将用户重定向到外部网址 我该怎么做 Tried System Web HttpContext Current Response Redirect 但没有成功 使用控制器的重定向 http msdn
  • 当前的 c++ 工作草案与当前标准有何不同

    通过搜索该标准的 PDF 版本 我最终找到了这个链接C 标准措辞草案 http www open std org jtc1 sc22 wg21 docs papers 2012 n3376 pdf从 2011 年开始 我意识到我可以购买最终
  • 如何识别 WPF 文本框中的 ValidationError 工具提示位置

    我添加了一个箭头来指示工具提示中的文本框 当文本框远离屏幕边缘时 这非常有效 但是当它靠近屏幕边缘时 工具提示位置发生变化 箭头显示在左侧 Here is the Image Correct as expected since TextBo
  • 在 2D 中将一个点旋转另一个点

    我想知道当一个点相对于另一个点旋转一定角度时如何计算出新的坐标 我有一个块箭头 想要将其相对于箭头底部中间的点旋转角度 theta 这是允许我在两个屏幕控件之间绘制多边形所必需的 我无法使用和旋转图像 从我到目前为止所考虑的情况来看 使问题
  • 一个模型可以通过多个编辑器模板传递吗?

    我尝试使用编辑器模板显示视图模型 该模板在应用基本对象编辑器模板之前将模型包装在字段集中 My view model Mvc3VanillaApplication Models ContactModel using Html BeginFo
  • 将数据打印到文件

    我已经超载了 lt lt 运算符 使其写入文件并写入控制台 我已经为同一个函数创建了 8 个线程 并且我想输出 hello hi 如果我在无限循环中运行这个线程例程 文件中的o p是 hello hi hello hi hello hi e
  • 单击关闭按钮后不显示 Google 一键登录 UI

    我正在尝试按照本指南使新的谷歌一键登录工作 https developers google com identity one tap web https developers google com identity one tap web
  • 为什么我不应该对不是由 malloc() 分配的变量调用 free() ?

    我在某处读到 使用它是灾难性的free删除不是通过调用创建的对象malloc 这是真的 为什么 这是未定义的行为 永远不要尝试它 让我们看看当您尝试时会发生什么free 自动变量 堆管理器必须推断出如何获取内存块的所有权 为此 它要么必须使
  • 耐用功能是否适合大量活动?

    我有一个场景 需要计算 500k 活动 都是小算盘 由于限制 我只能同时计算 30 个 想象一下下面的简单示例 FunctionName Crawl public static async Task
  • strcmp 给出分段错误[重复]

    这个问题在这里已经有答案了 这是我的代码给出分段错误 include
  • 什么是 __declspec 以及何时需要使用它?

    我见过这样的例子 declspec在我正在阅读的代码中 它是什么 我什么时候需要使用这个构造 这是 Microsoft 对 C 语言的特定扩展 它允许您使用存储类信息来赋予类型或函数属性 文档 declspec C https learn
  • 用于 C# XNA 的 Javascript(或类似)游戏脚本

    最近我准备用 XNA C 开发另一个游戏 上次我在 XNA C 中开发游戏时 遇到了必须向游戏中添加地图和可自定义数据的问题 每次我想添加新内容或更改游戏角色的某些值或其他内容时 我都必须重建整个游戏或其他内容 这可能需要相当长的时间 有没
  • 带重定向标准流的 C# + telnet 进程立即退出

    我正在尝试用 C 做一个 脚本化 telnet 项目 有点类似于Tcl期望 http expect nist gov 我需要为其启动 telnet 进程并重定向 和处理 其 stdin stdout 流 问题是 生成的 telnet 进程在
  • Googletest:如何异步运行测试?

    考虑到一个包含数千个测试的大型项目 其中一些测试需要几分钟才能完成 如果按顺序执行 整套测试需要一个多小时才能完成 通过并行执行测试可以减少测试时间 据我所知 没有办法直接从 googletest mock 做到这一点 就像 async选项
  • 使用 Crypto++ 获取 ECDSA 签名

    我必须使用 Crypto 在变量中获取 ECDSA 签名 我在启动 SignMessage 后尝试获取它 但签名为空 我怎样才能得到它 你看过 Crypto wiki 吗 上面有很多东西椭圆曲线数字签名算法 http www cryptop
  • 匿名结构体作为返回类型

    下面的代码编译得很好VC 19 00 23506 http rextester com GMUP11493 标志 Wall WX Za 与VC 19 10 25109 0 标志 Wall WX Za permissive 这可以在以下位置检

随机推荐

  • 如何从xslt中的java地图获取数据

    我需要从 XSLT 中的 Java 地图获取数据 我知道使用 xalan 我可以实现它 但我们依赖于通用 Transformer 这迫使我们使用 Saxon HE 我将 java 映射传递给变量并在 XSLT 中获取它 请建议我们如何实现这
  • 清除或重新创建 Ruby on Rails 数据库

    我有一个充满数据的开发 Ruby on Rails 数据库 我想删除所有内容并重建数据库 我正在考虑使用类似的东西 rake db recreate 这可能吗 我知道有两种方法可以做到这一点 这将重置您的数据库并重新加载当前架构 rake
  • 选择全日历中的整周

    我在使用 fullcalendar 插件时遇到了问题 我试图通过单击在月视图中选择整周 然后创建一个事件 换句话说 如果您单击特定周中的任何一天 该周将突出显示并创建一个事件 此后 该事件应输入我的数据库中 这是我到目前为止所拥有的
  • (w)ifstream 支持不同的编码吗

    当我使用 wifstream 将文本文件读取为宽字符串 std wstring 时 流实现是否支持不同的编码 即它可以用于读取例如ASCII UTF 8 和 UTF 16 文件 如果没有 我该怎么办 我需要阅读整个文件 如果这有影响的话 C
  • 空响应和未找到响应的 HTTP 状态代码

    我们正在实现基于 REST 的 Web 服务 并且对某些用例有一些疑问 考虑有一个唯一的帐户 其中包含一些信息 例如添加到购物车信息 如果不存在购物车信息 我们应该返回什么响应代码 例如 0 我们的理解是返回 200 并返回空响应 用户将购
  • assertj:比较 dto 和实体类之间的字段

    我需要比较一个DTO类及其Entity class 例如 一个AddressDTO类将是 Setter Getter NoArgsConstructor AllArgsConstructor public class AddressDTO
  • React CRA with CSP:拒绝执行内联脚本

    我已经使用以下方式建立了一个新网站Material UI 创建 React 模板 https github com mui org material ui tree master examples create react app 我添加了
  • agrep:只返回最佳匹配

    我在 R 中使用 agrep 函数 它返回匹配向量 我想要一个类似于 agrep 的函数 它只返回最佳匹配 或者如果存在平局则返回最佳匹配 目前 我正在对结果向量的每个元素使用 cba 包中的 sdist 函数来执行此操作 但这似乎非常多余
  • 在 IntelliJ 中的弹出 JavaDoc 上隐藏 JetBrains 注释

    有没有办法隐藏或turn off those 可用推断注释当我从方法中阅读弹出文档时 如下图所示 IntelliJ IDEA 中没有设置可以禁用它 I ve 提交了请求 https youtrack jetbrains com issue
  • 在 Elastic Beanstalk 上部署 NestJS 应用程序

    我正在尝试将我的 NestJS 应用程序部署到 AWS elastic beanstalk 但没有取得任何成功 有人可以一步步写下我如何实现这一目标吗 完整解释 我有一个带有 typeorm 的 Nestjs 应用程序 但没有将其配置为与
  • 什么允许匿名无参数委托类型不同?

    已读入 作为 C 3 0 中的委托和 Lambda 表达式 系列文章的一部分 短语 高级主题 无参数匿名方法 匿名方法可以省略参数列表 delegate return Console ReadLine 例如 这是非典型的 但确实如此允许相同
  • RSelenium 与 Tor 在 Windows 上具有新的 RSelenium 版本

    我发现 jdarrison 关于如何使用 Tor 启动这个很棒的答案RSelenium在窗户上 https stackoverflow com a 39048970 7837376 https stackoverflow com a 390
  • 与平台特定语言相比,使用 Adob​​e Air/Java 编写 Web 应用程序的优点/缺点?

    我需要为 Windows 和 Mac 也许还有 Linux 编写一个 Web 应用程序 也可以离线工作 我想知道我是否应该使用像air flash java 这样的东西 优点是我只需要编写一次应用程序 然而 我想知道这样做是否有任何缺点 而
  • Visual Studio 2022 未加载依赖项

    升级到 Visual Studio 2022 并安装 Net 6 0 SDK 后 我似乎在运行项目时遇到问题 每当我打开现有项目甚至创建新项目时 我都会收到以下依赖项错误 如果我尝试构建项目 我会收到错误 错误列表中没有任何错误 尝试了一些
  • Node.js 如何响应升级请求?

    我正在处理来自 Node js http 服务器的 websocket 升级 事件 升级处理程序的格式为 function req socket head 如果没有资源 我如何发送对此升级请求的响应目的 有没有办法使用套接字对象来做到这一点
  • Python 使用新的相机位置创建图像

    我现在正在努力完成一项特定的计算机视觉任务 例如 假设我们有一个道路的相机框架 现在我想用水平平移的假想相机生成一个新帧 此外 还添加了一个微小的摄像角度 为了说明这一点 我上传了一张演示图片 如何在 python 中从原始框架创建新框架
  • Oracle SQL:收到“没有匹配的唯一键或主键”错误,但不知道原因

    我在尝试创建表时收到此错误 但我不知道为什么 2016 07 05 14 08 02 42000 2270 ORA 02270 no matching unique or primary key for this column list 这
  • 为 Windows 中的目录生成校验和

    我想为目录创建校验和 我正在遵循对此给出的答案post https stackoverflow com questions 17228202 generate md5 keys and save in a text file 但问题是它正在
  • Java 中带有过期时间的对象池的第三方库

    我在 Web 服务服务器上 并且有具有内部连接的对象 初始化此连接需要很长时间 因此我的想法是使用对象池来重用不同请求之间的连接 这些对象连接到每个用户 因此我更喜欢使用用户名作为键 使用连接作为值 但我不想让连接永远打开 也许一段时间后
  • 接口,无法在Unity配置上构建

    我在这个项目上使用 Unity 时遇到问题 错误是 当前类型 Business Interfaces IPersonnelBusiness 是 接口 无法构造 您是否缺少类型映射 由于堆栈溢出 我已将 Unity 更新到最新版本issue