c# - 如何使用简单注入(inject)器在自定义 ClaimsPrincipal 中注入(inject)服务

标签 c# asp.net-mvc dependency-injection adfs simple-injector

我正在开发一个 ASP.Net MVC 项目,该项目使用 ADFS 进行身份验证并使用 SimpleInjector 作为 IoC 容器。应用程序的服务层在不同的项目中,服务在启动时注入(inject)到 Controller 构造函数中。其中一项服务是用户服务,我想用它从我的数据层获取用户信息等。

我有一个自定义委托(delegate)人(继承自 ClaimsPrincipal),我想在其中使用此用户服务并将用户信息存储在其中。我面临的问题是我不确定如何“粘合"自定义主体的用户服务。

我尝试在每次身份验证后获取用户服务实例并将其注入(inject)到身份中,但我收到一条错误消息,指出容器不包含服务实例。我的代码如下:

Application_Start()

    protected void Application_Start()
    {
        // Register the IoC container
        InjectorConfig.RegisterDependencies(_container);

        // RouteConfig etc...
    }

注入(inject)器配置

public class InjectorConfig
{
    /// <summary>
    /// Create the IoC container and register all dependencies
    /// </summary>
    public static void RegisterDependencies(Container container)
    {
        // Create the IoC container
        //var container = new Container();

        // Get the assembly that houses the services
        var serviceAssembly = typeof (UserService).Assembly;

        // Interate through the assembly and find all the services 
        var registrations = (
            from type in serviceAssembly.GetExportedTypes()
            where type.Namespace == "MyApp.Services"
            where type.GetInterfaces().Any()
            select new
            {
                Service = type.GetInterfaces().Single(), 
                Implementation = type,
            });

        // Register each of the services
        foreach (var registration in registrations)
        {
            container.Register(registration.Service, registration.Implementation, Lifestyle.Transient);
        }

        // Verify the container and set the MVC dependency resolver
        container.Verify();
        DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
    }
}

我的自定义 ClaimsPrincipal

public class MyCustomPrincipal : ClaimsPrincipal
{
    private readonly IUserService _userService;

    public MyCustomPrincipal(IIdentity identity, IUserService userService)
        :base(identity)
    {
        this._userService = userService;
    }

    public override bool IsInRole(string role)
    {
        return this._userService.IsInRole(this.Identity.GetUserId(), role);
    }
}

我的用户服务(在不同的程序集中)

public class UserService : IUserService
{
    public bool IsInRole(string currentUserId, string roleName)
    {
        // Check roles here
        return true;
    }
}

Application_PostAuthenticateRequest()

这是错误发生的地方。没有可用的实例

    protected void Application_PostAuthenticateRequest()
    {
        var currentUser = ClaimsPrincipal.Current.Identity;

        // This is where the error occurs. No instance available
        var userService = this._container.GetInstance<IUserService>();
        HttpContext.Current.User = new MyCustomPrincipal(currentUser, userService);
    }

我是 IoC 的新手,所以可能有一个简单的解决方案,但我正在用头撞墙(打个比方)试图解决这个问题。

如果您能提供任何帮助,我们将不胜感激!

已更新 这是异常详细信息

SimpleInjector.ActivationException was unhandled by user code
  HResult=-2146233088
  Message=No registration for type IUserService could be found.
  Source=SimpleInjector
  StackTrace:
       at SimpleInjector.Container.ThrowMissingInstanceProducerException(Type serviceType)
       at SimpleInjector.Container.GetInstanceFromProducer(InstanceProducer instanceProducer, Type serviceType)
       at SimpleInjector.Container.GetInstanceForType[TService]()
       at SimpleInjector.Container.GetInstance[TService]()
       at MyWebApp.Web.MvcApplication.Application_PostAuthenticateRequest() in c:\Projects\MyWebApp\Client\\MyWebApp.Web\Global.asax.cs:line 46
  InnerException: 

最佳答案

我能想到为什么会发生这种情况有 5 个可能的原因:

  1. UserService 类没有实现 IUserService。
  2. UserService 类不在命名空间“MyApp.Services”中。
  3. 该类是内部的。
  4. 您不小心创建了第二个(空)容器。
  5. 在调用 RegisterDependencies 之前调用 PostAuthentication 方法。

关于c# - 如何使用简单注入(inject)器在自定义 ClaimsPrincipal 中注入(inject)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28467707/

相关文章:

c# - 如何将变量值背后的代码绑定(bind)到javascript?

c# - RouteValueDictionary 值在 POST 上从字符串更改为数组

jquery - Bootstrap 样式输入类型的问题

asp.net-mvc - 在MVC中引用内容的正确方法

javascript - 似乎无法将 Angular-JWT 注入(inject)工厂

java - Wildfly 无法注入(inject)值(value)?

c# - 如何让.NET应用程序通过代理访问互联网

c# - Async-Await 在预期死锁的地方没有死锁

C# 将 XML 数据绑定(bind)到 ListView WPF

java - @Inject 注释如何知道在同一接口(interface)下实例化哪个具体类?