如何在Startup.cs中实例化此对象

时间:2017-02-13 07:43:06

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

我在基于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()时,我没有设置Object引用。这很明显。

因此,为了解决此错误,我将构造函数定义为。

 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
    }

如何实现会员资格等级。

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

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

1 个答案:

答案 0 :(得分: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);
    }

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