如何在静态方法中访问IServiceLocator实例,

时间:2016-03-04 12:40:15

标签: c# asp.net asp.net-mvc

public class SelectListItemHelper
{

    public static IServiceLocator serviceLocator;
    public static IServiceLocator ServiceLocator
    {
        set
        {
            if (value == null)
                throw new ArgumentNullException("value");
            if (serviceLocator != null)
                throw new Exception("HtmlHelperService cannot be set twice");
            serviceLocator = value;
        }
    }

    public static IEnumerable<SelectListItem> AccountList()
    {
        IList<SelectListItem> items = Using<GetAllAccounts>().Execute().Select(x => new SelectListItem
        {
            Value = x.AccountId.ToString(),
            Text = x.AccountName
        }).ToList();
        return items;
    }

    //Getting Error On this Method . Getting error "Object reference not set to an instance of an object" at serviceLocator.GetInstance<T>();

    private static T Using<T>() where T : class
    {
        var handler = serviceLocator.GetInstance<T>();
        if (handler == null)
        {
            throw new NullReferenceException("Unable to resolve type with service locator; type " + typeof(T).Name);
        }
        return handler;
    }

}

0 个答案:

没有答案