【问题标题】:how to instantiate this object in Startup.cs如何在 Startup.cs 中实例化这个对象
【发布时间】:2017-02-14 18:20:53
【问题描述】:

我在基于 Web api 的项目中使用基于 OAuth 令牌的身份验证。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");

        if (allowedOrigin == null) allowedOrigin = "*";

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

        //At this line, I am getting Error Object reference not set. 
        if (_membershipService.ValidateUser(context.UserName.Trim(), context.Password.Trim()))
        {
            var user = _membershipService.GetUser(context.UserName);

            /* db based authenication*/
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            identity.AddClaim(new Claim("sub", context.UserName));

            var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                { 
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                { 
                    "userName", user.Email
                },
                { 
                    "role", (user.Role).ToString()
                }
            });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
        }
        else
        {
            context.Rejected();
        }


    }

在调用 _membershipService.ValidateUser() 时,我收到未设置对象引用。这很明显。

所以为了修复这个错误,我将构造函数定义为。

 public SimpleAuthorizationServerProvider(IMembershipService membershipService)
    {
        _membershipService = membershipService;
    }

在调用方法时,我传递了引用。

Startup.cs

public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
           //passing the membership object.
            Provider = new SimpleAuthorizationServerProvider(_membershipService),

        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        //Token Consumption
        app.UseOAuthBearerAuthentication(OAuthBearerOptions);




    }

对象引用未设置为对象的实例。

所以我尝试重载 Startup.cs 的构造函数,如下所示:

public Startup(IMembershipservice membership)
{
    _membership = membership; 
}

但这会引发以下运行时错误

没有为此对象定义无参数构造函数。

Startup.cs

  public Startup()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
        RegisterIOC();
    }
 private void RegisterIOC()
    {
        container = new WindsorContainer();
        container.Register(Component.For<SimpleAuthorizationServerProvider>().LifestyleTransient());
     //rest of the stuff
    }

如何实例化 Membership Class。

(请注意,我使用的是 Castle Windsor DI Container)。

非常感谢任何帮助/建议。 谢谢。

【问题讨论】:

    标签: c# asp.net-web-api dependency-injection castle-windsor


    【解决方案1】:

    您说您正在使用 Castle Windsor DI 容器,但在 Startup.cs 类中没有初始化容器的代码。 如果您使用 OWIN(Startup.cs 类),则不需要在 Global.asax Application_Start 方法中进行应用程序初始化。 您应该将容器初始化移动到 Startup.cs 类并在初始化后解析 IMembershipservice 实例。 像这样的:

        public void Configuration(IAppBuilder app)
        {
    
            var container = new WindsorContainer().Install(new WindsorInstaller());
            container.Register(Component.For<IAppBuilder>().Instance(app));
            var httpDependencyResolver = new WindsorHttpDependencyResolver(container);
    
            HttpConfiguration config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
    
            config.DependencyResolver = httpDependencyResolver;
            GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new WindsorControllerActivator(container));
    
    
            app.UseWebApi(config);
        }
    

    然后你可以使用容器来解析你的类的实例。

    【讨论】:

    • DI 的东西在不同的地方,我重新检查过,所有的映射都到位了。但错误仍然存​​在
    • "DI 东西在不同的地方"
    • 但是为什么只有这个类会出错。所有控制器和服务都被正确实例化
    • 我正在调用 RegisterIOC()(一个私有方法)来完成它
    • 因为 Startup.cs 类现在是访问点。 Startup.cs 配置方法在 Global.asax 中的 Application_start 之前执行。因此,Application_start 中配置的 DI 无法解析 Startup.cs。答案就在这里msdn.microsoft.com/en-us/magazine/dn451439.aspx
    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多