接口,无法在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配置上构建 的相关文章

  • GLKit的GLKMatrix“列专业”如何?

    前提A 当谈论线性存储器中的 列主 矩阵时 列被一个接一个地指定 使得存储器中的前 4 个条目对应于矩阵中的第一列 另一方面 行主 矩阵被理解为依次指定行 以便内存中的前 4 个条目指定矩阵的第一行 A GLKMatrix4看起来像这样 u
  • Web 客户端和 Expect100Continue

    使用 WebClient C NET 时设置 Expect100Continue 的最佳方法是什么 我有下面的代码 我仍然在标题中看到 100 continue 愚蠢的 apache 仍然抱怨 505 错误 string url http
  • 为什么两个不同的 Base64 字符串的转换会返回相等的字节数组?

    我想知道为什么从 base64 字符串转换会为不同的字符串返回相同的字节数组 const string s1 dg const string s2 dq byte a1 Convert FromBase64String s1 byte a2
  • 在哪里可以找到列出 SSE 内在函数操作的官方参考资料?

    是否有官方参考列出了 GCC 的 SSE 内部函数的操作 即 头文件中的函数 除了 Intel 的 vol 2 PDF 手册外 还有一个在线内在指南 https www intel com content www us en docs in
  • 查找c中结构元素的偏移量

    struct a struct b int i float j x struct c int k float l y z 谁能解释一下如何找到偏移量int k这样我们就可以找到地址int i Use offsetof 找到从开始处的偏移量z
  • BitTorrent 追踪器宣布问题

    我花了一点业余时间编写 BitTorrent 客户端 主要是出于好奇 但部分是出于提高我的 C 技能的愿望 我一直在使用理论维基 http wiki theory org BitTorrentSpecification作为我的向导 我已经建
  • 表单身份验证 MVC4

    我正在尝试使用 MVC4 网站进行简单的表单身份验证设置 在App start FilterConfig cs中 public static void RegisterGlobalFilters GlobalFilterCollection
  • 用于登录 .NET 的堆栈跟踪

    我编写了一个 logger exceptionfactory 模块 它使用 System Diagnostics StackTrace 从调用方法及其声明类型中获取属性 但我注意到 如果我在 Visual Studio 之外以发布模式运行代
  • 不同枚举类型的范围和可转换性

    在什么条件下可以从一种枚举类型转换为另一种枚举类型 让我们考虑以下代码 include
  • 堆栈溢出:堆栈空间中重复的临时分配?

    struct MemBlock char mem 1024 MemBlock operator const MemBlock b const return MemBlock global void foo int step 0 if ste
  • 在 ASP.NET 5 中使用 DI 调用构造函数时解决依赖关系

    Web 上似乎充斥着如何在 ASP NET 5 中使用 DI 的示例 但没有一个示例显示如何调用构造函数并解决依赖关系 以下只是众多案例之一 http social technet microsoft com wiki contents a
  • HttpContext.GetGlobalResourceObject 始终返回 null

    我在 App GlobalResources 文件夹中创建了两个文件 SiteResources en US resx SiteResources sp SP resx 两者都包含 SiteTitleSeparator 的值 这是我想要做的
  • 创建链表而不将节点声明为指针

    我已经在谷歌和一些教科书上搜索了很长一段时间 我似乎无法理解为什么在构建链表时 节点需要是指针 例如 如果我有一个节点定义为 typedef struct Node int value struct Node next Node 为什么为了
  • 使用 Bearer Token 访问 IdentityServer4 上受保护的 API

    我试图寻找此问题的解决方案 但尚未找到正确的搜索文本 我的问题是 如何配置我的 IdentityServer 以便它也可以接受 授权带有 BearerTokens 的 Api 请求 我已经配置并运行了 IdentityServer4 我还在
  • 转发声明和包含

    在使用库时 无论是我自己的还是外部的 都有很多带有前向声明的类 根据情况 相同的类也包含在内 当我使用某个类时 我需要知道该类使用的某些对象是前向声明的还是 include d 原因是我想知道是否应该包含两个标题还是只包含一个标题 现在我知
  • 如何在整个 ASP .NET MVC 应用程序中需要授权

    我创建的应用程序中 除了启用登录的操作之外的每个操作都应该超出未登录用户的限制 我应该添加 Authorize 每个班级标题前的注释 像这儿 namespace WebApplication2 Controllers Authorize p
  • 将控制台重定向到 .NET 程序中的字符串

    如何重定向写入控制台的任何内容以写入字符串 对于您自己的流程 Console SetOut http msdn microsoft com en us library system console setout aspx并将其重定向到构建在
  • C# 模拟VolumeMute按下

    我得到以下代码来模拟音量静音按键 DllImport coredll dll SetLastError true static extern void keybd event byte bVk byte bScan int dwFlags
  • 哪种 C 数据类型可以表示 40 位二进制数?

    我需要表示一个40位的二进制数 应该使用哪种 C 数据类型来处理这个问题 如果您使用的是 C99 或 C11 兼容编译器 则使用int least64 t以获得最大的兼容性 或者 如果您想要无符号类型 uint least64 t 这些都定
  • 良好的 WiX 编辑器 [重复]

    这个问题在这里已经有答案了 我目前正在开发一个使用 WiX 创建 MSI 的项目 我过去在 Sourceforge 上使用 WiXEdit 来管理包含在 WiX 项目中的文件 因为它比直接操作 XML 稍微容易一些 但它仍然有点笨重 有谁知

随机推荐

  • 如何从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