如何使用Simple Injector在自定义ClaimsPrincipal中注入服务

时间:2015-02-12 01:23:56

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

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

我有一个自定义Principal(继承自ClaimsPrincipal),我想使用此用户服务并存储用户信息。我面临的问题是我不确定如何" "自定义主体的用户服务。

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

的Application_Start()

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

        // RouteConfig etc...
    }

InjectorConfig

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: 

1 个答案:

答案 0 :(得分:1)

我可以想出为什么会发生这种情况的原因有五种:

  1. UserService类未实现IUserService。
  2. UserService类不在命名空间&#34; MyApp.Services&#34;。
  3. 班级是内部的。
  4. 您不小心创建了第二个(空)容器。
  5. 在调用RegisterDependencies之前调用PostAuthentication方法。