gpt4 book ai didi

c# - Unity 4(IOC) + MVC 5 在启动期间无法解析类型

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:21 28 4
gpt4 key购买 nike

我将 Unity 4(通过 NuGet)与 ASP.NET MVC 5 结合使用。我修改了所有 Controller 和业务类,以通过它们的构造函数接收它们的依赖项作为接口(interface)。

boostrapper 类包含以下代码:

public class Bootstrapper
{
public static IUnityContainer UnityContainer { get; set; }

public static void Initialize()
{
InitializeUnity();
RegisterTypes();
}

private static void InitializeUnity()
{
UnityContainer = UnityConfig.GetConfiguredContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(UnityContainer));
}

private static void RegisterTypes()
{
new Core.Bootstrapper().RegisterTypes(UnityContainer);
}
}

Core.Bootstrapper().RegisterTypes的内容如下:

public IUnityContainer RegisterTypes(IUnityContainer container)
{
// Register repositories
container.RegisterType<IRepository, Repository>()
.RegisterType<IBdeRepository, BdeRepository>()
.RegisterType<IDocumentRepository, DocumentRepository>()
.RegisterType<IHampRepository, HampRepository>()
.RegisterType<IReportsRepository, ReportsRepository>()
.RegisterType<ITransactionRepository, TransactionRepository>();

// Register commands
container.RegisterType<IBaseCommand, BaseCommand>()
.RegisterType<IDailyLetterInfoUpdate, DailyLetterInfoUpdate>()
.RegisterType<IDailyReconciliation, DailyReconciliation>()
.RegisterType<InsertNewRows, InsertNewRows>()
.RegisterType<IOrderDailyLM023, OrderDailyLM023>()
.RegisterType<IOrderMonthlyLM012, OrderMonthlyLM012>()
.RegisterType<IOrderMonthlyLM014, OrderMonthlyLM014>()
.RegisterType<IPerformMonthlyRecastStatusUpdate, PerformMonthlyRecastStatusUpdate>()
.RegisterType<IUpdateReissuedRecasts, UpdateReissuedRecasts>();

// Register utility types
container.RegisterType<ICsvExporter, CsvExporter>()
.RegisterType<ILogger, Logger>();

return container;
}

最后,UnityConfig.cs 和 UnityMvcActivator.cs 与它们首次由 NuGet 包安装时的状态相比保持不变。

当我启动我的 MVC 应用程序时,我遇到了以下错误消息:

Resolution of the dependency failed, type = "System.Web.Mvc.ITempDataProviderFactory", name = "(none)".

Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, System.Web.Mvc.ITempDataProviderFactory, is an interface and cannot be constructed. Are you missing a type mapping?

它提到的类似乎是 MVC 本身内部的东西,这让我相信我在配置 Unity 时错过了一些东西,或者我在这样做时搞砸了一些东西。然而,对于我的生活,我无法弄清楚它是什么,尽管我已经咨询了几乎所有我能找到的关于 StackOverflow 上错误消息的问题。 (到目前为止,所提出的解决方案都没有解决问题,但很可能我遗漏了一些东西。)

谁能看到我忽略的东西?我做错了什么?

更新:

这里抛出异常:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapMvcAttributeRoutes(); // Exception thrown on this line.
}

最佳答案

这里有一个略有不同的实现,其中对 MVC 部分进行了特定排除,改编自 UnityDependencyResolver.cs 处的代码。

似乎在启动时有轻微的性能优势,但主要是您不会引发 10 次异常。

/// <summary>
/// Resolves dependencies against the current DI container.
/// </summary>
public class UnityDependencyResolver : IDependencyResolver
{
private readonly IUnityContainer container;
// NB Not likely to be be big but will be frequent so use HashSet as O(1) lookup cost - see https://stackoverflow.com/questions/18651940/performance-benchmarking-of-contains-exists-and-any
private readonly HashSet<Type> excludedTypes;

/// <summary>
/// Initializes a new instance of the <see cref="UnityDependencyResolver"/> class.
/// </summary>
/// <param name="container">The container.</param>
public UnityDependencyResolver(IUnityContainer container)
{
this.container = container;
excludedTypes = new HashSet<Type>();

StandardExclusions();
}

/// <summary>
/// Resolves an instance of the default requested type from the container.
/// </summary>
/// <param name="serviceType">The <see cref="Type"/> of the object to get from the container.</param>
/// <returns>The requested object.</returns>
public object GetService(Type serviceType)
{
if (typeof(IController).IsAssignableFrom(serviceType))
{
return container.Resolve(serviceType);
}

try
{
return excludedTypes.Contains(serviceType) ? null : container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}

/// <summary>
/// Resolves multiply registered services.
/// </summary>
/// <param name="serviceType">The type of the requested services.</param>
/// <returns>The requested services.</returns>
public IEnumerable<object> GetServices(Type serviceType)
{
return container.ResolveAll(serviceType);
}

public void Exclude<T>()
{
Exclude(typeof(T));
}

public void Exclude(Type type)
{
excludedTypes.Add(type);
}

public void Include<T>()
{
Include(typeof(T));
}

public void Include(Type type)
{
excludedTypes.Remove(type);
}

private void StandardExclusions()
{
Exclude<System.Web.Mvc.IControllerFactory>();
Exclude<System.Web.Mvc.IControllerActivator>();
Exclude<System.Web.Mvc.ITempDataProviderFactory>();
Exclude<System.Web.Mvc.ITempDataProvider>();
Exclude<System.Web.Mvc.Async.IAsyncActionInvokerFactory>();
Exclude<System.Web.Mvc.IActionInvokerFactory>();
Exclude<System.Web.Mvc.Async.IAsyncActionInvoker>();
Exclude<System.Web.Mvc.IActionInvoker>();
Exclude<System.Web.Mvc.IViewPageActivator>();
Exclude<System.Web.Mvc.ModelMetadataProvider>();
}
}

如果您确实覆盖了标准 MVC 接口(interface)之一,那么您可以使用以下命令将其从排除列表中删除

var resolver = new UnityDependencyResolver(container);
resolver.Include<System.Web.Mvc.IActionInvoker>();

关于c# - Unity 4(IOC) + MVC 5 在启动期间无法解析类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42659400/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com