【发布时间】:2016-07-06 12:09:36
【问题描述】:
尝试从我的 ASP.NET MVC 控制器操作访问单例类时出现空引用异常。我使用 Autofac 作为 IoC 容器。
代码如下:
注册依赖方法:
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
const string nameOrConnectionString = "name=DefaultConnection";
builder.RegisterApiControllers(typeof(WebApiConfig).Assembly);
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterGeneric(typeof(EntityRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(Service<>)).As(typeof(IService<>)).InstancePerLifetimeScope();
builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerLifetimeScope();
builder.Register<IEntitiesContext>(b =>
{
var logger = b.Resolve<ILogger>();
var context = new InterfaceContext(nameOrConnectionString, logger);
return context;
}).InstancePerRequest();
builder.Register(b => NLogLogger.Instance).SingleInstance();
builder.Register(b => UserControlHelper.Instance).SingleInstance();
builder.RegisterModule(new IdentityModule());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver =
new AutofacWebApiDependencyResolver(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
UserControlHelper 类:
public class UserControlHelper
{
private static volatile UserControlHelper _instance;
private static readonly object SyncRoot = new object();
private static IService<Administrator> _service;
private static IService<Customer> _customerService;
private UserControlHelper() { }
private UserControlHelper(IService<Administrator> service, IService<Customer> customerService)
{
_service = service;
_customerService = customerService;
}
public static UserControlHelper Instance
{
get
{
if (_instance == null)
{
lock (SyncRoot)
{
if (_instance == null)
_instance = new UserControlHelper(_service, _customerService);
}
}
return _instance;
}
}
public static string GetUserData(int userId, string type)
{
var getImage = _service.GetByIdAsync(userId);
switch (type)
{
case "Image":
{
return getImage.GetAwaiter().GetResult().Image;
}
case "Name":
{
return getImage.GetAwaiter().GetResult().FullName;
}
case "Email":
{
return getImage.GetAwaiter().GetResult().Email;
}
case "AllUsers":
{
return _customerService.GetCountAsync(userId).GetAwaiter().GetResult().ToString();
}
default:
return "No Data";
}
}
}
我这样称呼它:
ViewBag.FullName = UserControlHelper.GetUserData(UserId, "Name");
【问题讨论】:
标签: c# asp.net-mvc autofac