草庐IT

c# - 翻译 ninject ISecureDataFormat 绑定(bind)到 Autofac

coder 2024-05-23 原文

我正在将一个大型代码库从 Ninject 迁移到 Autofac,并且正在努力处理其中一个绑定(bind)(根据我的一些调试,我认为这会导致激活错误)。

注入(inject):

Bind<ISecureDataFormat<AuthenticationTicket>>()
     .ToMethod(context =>
         {
             var owinContext = context.Kernel.Get<IOwinContext>();
             return owinContext
                    .Get<ISecureDataFormat<AuthenticationTicket>>("SecureDataFormat");
         });

Autofac(我有什么):

builder.Register(
    context => context.Resolve<IOwinContext>()
        .Get<ISecureDataFormat<AuthenticationTicket>>("SecureDataFormat"))
        .As<ISecureDataFormat<AuthenticationTicket>>();

启动.cs:

var container = RegisterIoC(app, config);

public IContainer RegisterIoC(IAppBuilder app, HttpConfiguration config)
    {
        var builder = new ContainerBuilder();
        builder = RegisterDependencies(builder);
        builder = RegisterFilters(builder, config);

        /*builder.RegisterModule<DebuggingRequestModule>();*/

        var container = builder.Build();

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        app.UseAutofacMiddleware(container);
        app.UseAutofacMvc();
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

        return container;
    }

更多:

builder.RegisterModule<ApiDependencyModule>().RegisterModule<AutofacWebTypesModule>();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterApiControllers(typeof(AccountController).Assembly);

(看似)关联​​的构造函数:

账户 Controller .cs:

public AccountController(ILoginService loginService,
                             IBearerTokenStore tokenStore,
                             IRememberMeCookieService rememberMeCookieService,
                             IInternalSsoChallenge ssoChallenge)
{
}

登录服务.cs:

public LoginService(IBearerTokenStore tokenStore, 
        IGrantTypeProvider grantProvider, 
        IRememberMeCookieService rememberMeCookieService)
{
}

BearerTokenCookieStore.cs:

public BearerTokenCookieStore(IOwinContext owinContext, ISecureDataFormat<AuthenticationTicket> secureDataFormat, IAppSettingsReader appSettingsReader, ICookieService cookieService)
{
}

我有一个帮助我调试的日志记录模块,这是我拥有的消息列表

Resolving  _______.Login.Controllers.AccountController
--Resolving  _______.ApiGateway.Services.Auth.LoginService
----Resolving  _______.ApiGateway.Security.OAuth.BearerTokenCookieStore
------Resolving  Microsoft.Owin.Security.DataHandler.SecureDataFormat`1[Microsoft.Owin.Security.AuthenticationTicket]
Exception thrown: 'Autofac.Core.DependencyResolutionException' in Autofac.dll
Exception thrown: 'Autofac.Core.DependencyResolutionException' in Autofac.dll
Exception thrown: 'Autofac.Core.DependencyResolutionException' in Autofac.dll
The thread 0x1014 has exited with code 0 (0x0).

编辑:

我看到的异常:

An error occurred during the activation of a particular registration.
See the inner exception for details. Registration: 
Activator = AccountController (DelegateActivator), 
Services = [____.Login.Controllers.AccountController], 
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, 
Sharing = None, 
Ownership = ExternallyOwned ---> 
An error occurred during the activation of a particular registration. 
See the inner exception for details. 
Registration: 
Activator = AccountController (ReflectionActivator), 
Services = [____.Login.Controllers.AccountController], 
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, 
Sharing = None, Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. 
See the inner exception for details. 
Registration: 
Activator = LoginService (DelegateActivator), 
    Services = [____.ApiGateway.Services.Auth.ILoginService],
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime,
Sharing = None,
Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = LoginService (ReflectionActivator),
Services = [____.ApiGateway.Services.Auth.ILoginService],
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime,
Sharing = None,
Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = BearerTokenCookieStore (DelegateActivator),
Services = [____.ApiGateway.Security.OAuth.IBearerTokenStore],
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime,
Sharing = None,
Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = BearerTokenCookieStore (ReflectionActivator),
Services = [____.ApiGateway.Security.OAuth.IBearerTokenStore],
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime,
Sharing = Shared,
Ownership = OwnedByLifetimeScope ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ISecureDataFormat`1 (DelegateActivator),
Services = [Microsoft.Owin.Security.ISecureDataFormat`1[[Microsoft.Owin.Security.AuthenticationTicket,
Microsoft.Owin.Security,
Version=3.0.1.0,
Culture=neutral,
PublicKeyToken=31bf3856ad364e35]]],
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime,
Sharing = None,
Ownership = ExternallyOwned ---> An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = ISecureDataFormat`1 (DelegateActivator),
Services = [Microsoft.Owin.Security.ISecureDataFormat`1[[Microsoft.Owin.Security.AuthenticationTicket,
Microsoft.Owin.Security,
Version=3.0.1.0,
Culture=neutral,
PublicKeyToken=31bf3856ad364e35]]],
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime,
Sharing = None,
Ownership = OwnedByLifetimeScope ---> A delegate registered to create instances of 'Microsoft.Owin.Security.ISecureDataFormat`1[Microsoft.Owin.Security.AuthenticationTicket]' returned null. (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.) (See inner exception for details.)

最里面:

A delegate registered to create instances of 'Microsoft.Owin.Security.ISecureDataFormat`1[Microsoft.Owin.Security.AuthenticationTicket]' returned null.

最佳答案

我们可以将 autofac 与那些 c# owin 控制反转(ninject to autofac)一起使用,一般如下所示

Startup.cs

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {

            var config = new HttpConfiguration();
            WebApiConfig.Register(config);    

            ConfigureIoC(app, config);
            Components.Config();

            Auth.ConfigureForApi(app);

            app.UseAutofacWebApi(config);
            app.UseCors(CorsOptions.AllowAll);
            app.UseWebApi(config);
            config.EnsureInitialized();
        }

        private void ConfigureIoC(IAppBuilder app, HttpConfiguration config)
        {
            IoC.RegisterModules(
                builder =>
                {
                    builder.Register<IAuthenticationManager>(c => c.Resolve<IOwinContext>().Authentication).InstancePerRequest();
                    builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();
                    builder.RegisterApiControllers(typeof(Startup).Assembly).PropertiesAutowired();
                },
                container =>
                {
                    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
                    app.UseAutofacMiddleware(container);

                },
                true
                );
        }

    }

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }
}

组件配置:

public static class Components
{
    public static void Config() {
        TypeAdapterConfig.GlobalSettings.AllowImplicitDestinationInheritance = true;
        var registers = new List<IRegister>();
        registers.Add(new DtoMapping());
        registers.Add(new MappingRegistration());
        TypeAdapterConfig.GlobalSettings.Apply(registers);

        ObjectMapper.Current = new MapsterAdapter();
        DbConfiguration.Loaded += DbConfiguration_Loaded;

        var r = new Registrations();
        r.Run();
    }


    private static void DbConfiguration_Loaded(object sender, System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationLoadedEventArgs e)
    {
        e.ReplaceService<DbProviderServices>((s, k) => System.Data.Entity.SqlServer.SqlProviderServices.Instance);
    }

}

身份验证:

public class Auth
    {
        public static void ConfigureForMvc(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Login"),

                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, UserEntity, int>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) =>
                        user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie),
                        getUserIdCallback: (Identity) => Identity.GetUserId<int>())
                }
            });
        }

        public static void ConfigureForApi(IAppBuilder app)
        {
            var OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/oauth2/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(120),
                Provider = new CustomOAuthProvider(),
                AccessTokenFormat = new CustomJwtFormat(ConfigConstants.Issuer)
            };

            app.UseOAuthAuthorizationServer(OAuthServerOptions);

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { ConfigConstants.AudienceId },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(ConfigConstants.Issuer, ConfigConstants.AudienceSecurityKey)
                    }
                });

        }
    }

关于c# - 翻译 ninject ISecureDataFormat 绑定(bind)到 Autofac,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49536492/

有关c# - 翻译 ninject ISecureDataFormat 绑定(bind)到 Autofac的更多相关文章

  1. ruby - i18n Assets 管理/翻译 UI - 2

    我正在使用i18n从头开始​​构建一个多语言网络应用程序,虽然我自己可以处理一大堆yml文件,但我说的语言(非常)有限,最终我想寻求外部帮助帮助。我想知道这里是否有人在使用UI插件/gem(与django上的django-rosetta不同)来处理多个翻译器,其中一些翻译器不愿意或无法处理存储库中的100多个文件,处理语言数据。谢谢&问候,安德拉斯(如果您已经在ruby​​onrails-talk上遇到了这个问题,我们深表歉意) 最佳答案 有一个rails3branchofthetolkgem在github上。您可以通过在Gemfi

  2. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  3. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  4. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

  5. 基于C#实现简易绘图工具【100010177】 - 2

    C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.

  6. ruby-on-rails - 创建 ruby​​ 数据库时惰性符号绑定(bind)失败 - 2

    我正在尝试在Rails上安装ruby​​,到目前为止一切都已安装,但是当我尝试使用rakedb:create创建数据库时,我收到一个奇怪的错误:dyld:lazysymbolbindingfailed:Symbolnotfound:_mysql_get_client_infoReferencedfrom:/Library/Ruby/Gems/1.8/gems/mysql2-0.3.11/lib/mysql2/mysql2.bundleExpectedin:flatnamespacedyld:Symbolnotfound:_mysql_get_client_infoReferencedf

  7. ruby - Google-api-ruby-client 翻译 API 示例 - 2

    很高兴看到google代码:google-api-ruby-client项目,因为这对我来说意味着Ruby人员可以使用GoogleAPI-s来完善代码。虽然我现在很困惑,因为给出的唯一示例使用Buzz,并且根据我的实验,Google翻译(v2)api的行为必须与google-api-ruby-client中的Buzz完全不同。.我对“Explorer”演示示例很感兴趣——但据我所知,它并不是一个探索器。它所做的只是调用一个Buzz服务,然后浏览它已经知道的关于Buzz服务的事情。对我来说,Explorer应该让您“发现”所公开的服务和方法/功能,而不一定已经知道它们。我很想听听使用这个

  8. ruby-on-rails - 如果特定语言环境中缺少翻译,如何配置 i18n 以使用 en 语言环境? - 2

    如果特定语言环境中缺少翻译,如何配置i18n以使用en语言环境翻译?当前已插入翻译缺失消息。我正在使用RoR3.1。 最佳答案 找到相似的question这里是答案:#application.rb#railswillfallbacktoconfig.i18n.default_localetranslationconfig.i18n.fallbacks=true#railswillfallbacktoen,nomatterwhatissetasconfig.i18n.default_localeconfig.i18n.fallback

  9. ruby - ruby 中绑定(bind)对象的实际使用 - 2

    昨晚,我在思考我认为是高级ruby​​语言的功能,即Continuations(callcc)和Bindingobjects。我的意思是高级,因为我有静态类型的oo语言背景(C#、Java、C++),我最近才发现ruby​​,所以这些语言特性对我来说不是很熟悉。我想知道这些语言功能在现实世界中的用途是什么。根据我的经验,一切都可以用静态类型的oo语言来完成,但有时我不太同意。我想我在阅读SamRuby的那篇好文章时发现了Continuation的美妙之处/兴趣:http://www.intertwingly.net/blog/2005/04/13/Continuations-for-C

  10. ruby-on-rails - 如何使用 globalize 和 rails 4 以一种形式显示所有翻译字段 - 2

    在使用rails4和https://github.com/globalize/globalize的情况下,我应该如何为我的模型编写表单?用于翻译。我想以一种形式显示所有翻译,如下例所示。我在这里找到了解决方案https://github.com/rilla/batch_translations但我不知道如何实现它。这个“批量翻译”是一个gem还是什么?以及如何安装它。EditingpostEnglish(defaultlocale)SpanishtranslationFrenchtranslation 最佳答案 批处理翻译gem很旧

随机推荐