Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将ninject ISecureDataFormat绑定转换为Autofac_C#_Owin_Inversion Of Control_Ninject_Autofac - Fatal编程技术网

C# 将ninject ISecureDataFormat绑定转换为Autofac

C# 将ninject ISecureDataFormat绑定转换为Autofac,c#,owin,inversion-of-control,ninject,autofac,C#,Owin,Inversion Of Control,Ninject,Autofac,我正在将一个大型的代码库从Ninject迁移到Autofac,并且正在其中一个绑定上苦苦挣扎(我相信这会导致基于我的一些调试的激活错误) Ninject: Bind<ISecureDataFormat<AuthenticationTicket>>() .ToMethod(context => { var owinContext = context.Kernel.Get<IOwinContext>();

我正在将一个大型的代码库从Ninject迁移到Autofac,并且正在其中一个绑定上苦苦挣扎(我相信这会导致基于我的一些调试的激活错误)

Ninject:

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

public LoginService(IBearerTokenStore tokenStore, 
        IGrantTypeProvider grantProvider, 
        IRememberMeCookieService rememberMeCookieService)
{
}
BearerTokenCookieStore.cs:

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

我看到的例外情况是:

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与控制反转(ninject to autofac)中的c#owin一起使用,一般如下所示

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
                );
        }

    }
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)
                    }
                });

        }
    }
公共静态类组件
{
公共静态void Config(){
TypeAdapterConfig.GlobalSettings.AllowImplicitDestinationInheritance=true;
变量寄存器=新列表();
registers.Add(新的DtoMapping());
registers.Add(新的MappingRegistration());
TypeAdapterConfig.GlobalSettings.Apply(寄存器);
ObjectMapper.Current=new MapsterAdapter();
DbConfiguration.Loaded+=DbConfiguration\u Loaded;
var r=新注册();
r、 Run();
}
已加载私有静态无效DbConfiguration_(对象发送方,System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationLoadedEventArgs e)
{
e、 ReplaceService((s,k)=>System.Data.Entity.SqlServer.SqlProviderServices.Instance);
}
}
身份验证:

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)
                    }
                });

        }
    }
公共类身份验证
{
公共静态无效配置FormVC(IAppBuilder应用程序)
{
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=DefaultAuthenticationTypes.ApplicationOkie,
LoginPath=新路径字符串(“/Login”),
Provider=新CookieAuthenticationProvider
{
OnValidateIdentity=SecurityStampValidator.OnValidateIdentity(
validateInterval:TimeSpan.FromMinutes(30),
regenerateIdentityCallback:(管理者,用户)=>
user.GenerateUserIdentityAsync(manager,DefaultAuthenticationTypes.ApplicationOkie),
getUserIdCallback:(标识)=>Identity.GetUserId()
}
});
}
API的公共静态无效配置(IAppBuilder应用程序)
{
var OAuthServerOptions=新的OAuthAuthorizationServerOptions()
{
AllowInsecureHttp=true,
TokenEndpointPath=新路径字符串(“/oauth2/token”),
AccessTokenExpireTimeSpan=TimeSpan.FromMinutes(120),
Provider=新的CustomOAuthProvider(),
AccessTokenFormat=新的CustomJwtFormat(ConfigConstants.Issuer)
};
使用OAuthAuthorizationServer(OAuthServerOptions);
app.UseJwtBearerAuthentication(
新的JWTBeareAuthenticationOptions
{
AuthenticationMode=AuthenticationMode.Active,
AllowedAudients=new[]{ConfigConstants.audenceId},
IssuerSecurityTokenProviders=新的IIssuerSecurityTokenProvider[]
{
新的SymmetriceIsuerSecurityTokenProvider(ConfigConstants.Issuer,ConfigConstants.AudienceSecurityKey)
}
});
}
}

我确实在问题中包括了以前正常工作的ninject设置和失败的autofac设置。你能添加你的启动吗?您是否正在为owin使用autofac?您是否添加了
app.UseAutofac(container)
?@mutmart-您是否也可以包含packages.xml(只包含owin/webapi/mvc/autofac依赖项就足够了)。在初创企业中,一件奇怪的事情是将类似MVC4的引导与较新的引导混合在一起。我们没有packages.xml文件……老实说,我应该在我还拥有代码库的时候回答这个问题。我必须找到一个仍然在我以前的雇主工作的人来找到最终的解决方案。我相信我改变了注射的结构
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)
                    }
                });

        }
    }