如何初始化接口类 [英] How to initialize a interface class

查看:169
本文介绍了如何初始化接口类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前遇到以下错误 - 对象引用未设置为对象的实例。在下面的代码中:

I am currently experiencing the following error -- Object reference not set to an instance of an object." on the code below:

api_login user = Repository.Validate2(userName, password);




public class BasicAuthMessageHandler : DelegatingHandler
    {

        private const string BasicAuthResponseHeader = "WWW-Authenticate";
        private const string BasicAuthResponseHeaderValue = "Basic";

        //[Inject]
        //public iUser Repository { get; set; }

        private readonly iUser Repository;


        private bool TryGetPrincipal(string userName, string password, out IPrincipal principal)
        {
            // this is the method that authenticates against my repository (in this case, hard coded)
            // you can replace this with whatever logic you'd use, but proper separation would put the
            // data access in a repository or separate layer/library.
            api_login user = Repository.Validate2(userName, password);

            if (user.username != null)
            {
                // once the user is verified, assign it to an IPrincipal with the identity name and applicable roles
                //principal = new GenericPrincipal(new GenericIdentity(user.username));
                principal = new GenericPrincipal(new GenericIdentity(user.username), System.Web.Security.Roles.GetRolesForUser(user.role));
                return true;
            }

            principal = null;
            return false;
        }
    }







public interface iUser
    {
        api_login GetData(string userName);
        api_login Validate2(string userName, string Password);

    }







namespace API_09Oct
{
    public class User : iUser
    {
        //private cdwEntities db = new cdwEntities();

        private cdwEntities2 db;

       public User()
        {
             db = new cdwEntities2();
        }

       public User(cdwEntities2 context)
        {
          db = context;
        }

       public api_login Validate2(string userName, string Password)
       {
         //logic
       }

    }





我有点挣扎,怎么做我在basicAuthHandler类中初始化一个接口类?

请帮助。非常感谢。



I am little struggling, in how do I initialize an interface class in the basicAuthHandler class?
Please help. Many thanks.

推荐答案

实际上有两种方法可以做到这一点。第一种方法是在尝试访问存储库之前执行类似的操作
There are, effectively, two ways that you can do this. The first way would be to do something like this before you attempt to access Repository
if (Repository == null)
  Repository = new User();

这样可行,因为您已经实现了 iUser 用户类的接口(作为一个注释,你应该在接口上加上大写字母I)。



第二种方式(也是我更喜欢的方式)是使用依赖注入将iUser实现注入 BasicAuthMessageHandler 。基本上,你会有一个看起来像这样的构造函数(假设你使用构造函数注入):

This would work because you have implemented the iUser interface on your User class (as a note, you should really prefix interfaces with a capital I).

A second way (and the one I prefer) would be to use Dependency Injection to inject the iUser implementation into BasicAuthMessageHandler. Basically, you would have a constructor that looked like this (assuming you use constructor injection):

public BasicAuthMessageHandler(iUser repository)
{
  if (repository == null) throw new ArgumentNulLException("repository");
  Repository = repository;
}

例如,如果你使用的是Unity,你可以像这样注册你的用户实现:

As an example, if you were using Unity, you would register your User implementation like this:

MyUnityContainer.RegisterInterface<iUser, User>(new ContainerControlledLifetime());

现在,这种方法确实依赖于你有基础设施来处理DI - 如果你没有这个使用我展示的第一种方法。

Now, this approach does rely on you having the infrastructure in place to handle DI - if you don't have this in place, use the first method I showed.


您需要创建一个实现iUser接口的类的实例并将其分配给Repository。你不能在空实例上调用方法!而且,你不能有一个静态的接口方法,所以...



可能你想要的不是一个接口而是一个抽象类,它可以有(非抽象的静态方法。然后,您将Validate2声明为抽象UserBase类的静态成员,并且它可以返回User实例。讨厌但......
You need to create an instance of a class that implements the iUser interface and assign it to Repository. You can't call a method on an empty instance! And, you can't have a static Interface method, so...

Probably, what you want is not an interface but an abstract class, which can have (non-abstract) static methods. You would then declare Validate2 as a static member of the abstract UserBase class, and it could return a User instance. Nasty though...


这篇关于如何初始化接口类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆