【问题标题】:Asp.Net MVC Unity dependency injection gives an exception when trying to resolve a controllerAsp.Net MVC Unity 依赖注入在尝试解析控制器时出现异常
【发布时间】:2018-12-05 23:31:37
【问题描述】:

我第一次尝试实现依赖注入。我基于我公司的其他工作项目和网络内容。

我遇到了解析器尝试解析控制器类型的情况。我没有注册任何控制器类型(还没有看到类似的东西),所以我很困惑。

这是我在Global.asax.cs注册的:

Container = new UnityContainer();
        
// repositories
foreach (var type in Assembly.GetAssembly(typeof(UserRepository))
                    .GetTypes()
                    .Where(x => x.IsClass && x.Name.EndsWith("Repository")))
{
    Container.RegisterType(type);
}

// services
foreach (var type in Assembly.GetAssembly(typeof (TaskService))
                    .GetTypes()
                    .Where(x => x.IsClass && x.Name.EndsWith("Service")))
{
    Container.RegisterType(type);
}

DependencyResolver.SetResolver(new UnityDependencyResolver(Container));

这里是发生异常的UnityDependencyResolver方法:

private readonly IUnityContainer _container;

public UnityDependencyResolver(IUnityContainer container)
{
    this._container = container;
}

public object GetService(Type serviceType)
{
    if (!_container.IsRegistered(serviceType))
    {
        if (serviceType.IsAbstract || serviceType.IsInterface)
        {
            return null;
        }
    }
    return _container.Resolve(serviceType); // Right on this line the exception occurs
}

这是异常正文(full text here):

Microsoft.Practices.Unity.dll 中出现“Microsoft.Practices.Unity.ResolutionFailedException”类型的异常,但未在用户代码中处理

附加信息:依赖解析失败,type = "Tasks.Controllers.TasksController", name = "(none)"。

在解决时发生异常。

异常是:InvalidOperationException - 当前类型 NHibernate.ISessionFactory 是一个接口,无法构造。您是否缺少类型映射?

如您所见,当解析器获取要解析的 TasksController 类型(在 serviceType 中)并崩溃时,就会出现问题。

这是我的控制器的相关部分(这是项目中唯一的注入),如果有帮助的话:

protected TaskService TaskService { get; set; }

public TasksController(TaskService taskService)
{
    this.TaskService = taskService;
}

为什么会这样?

【问题讨论】:

标签: c# asp.net-mvc nhibernate dependency-injection unity-container


【解决方案1】:

有一个名为“Unity bootstraper for ASP.NET MVC”的 NuGet 包专门针对 ASP.NET MVC Web 应用程序,你试过吗?基本上安装好后,只需在 App_Start 文件夹下的 UnityConfig.cs 中注册你想要注入的内容就可以了。

例如:

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

    // TODO: Register your types here
    container.RegisterType<IAuthProvider, FormsAuthProvider>();
}

IAuthProvider 是接口,FormsAuthProvider 是实际实现

【讨论】:

  • 谢谢老哥,我去看看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
  • 2018-03-06
  • 1970-01-01
  • 2019-07-20
相关资源
最近更新 更多