![](/img/trans.png)
[英]NullReferenceException error in Unity when trying to get data from a static class
[英]Microsoft Unity error when resolving repository from console app - NullReferenceException
从控制台应用程序调用存储库时,我在解析存储库时遇到问题。 正常运行应用程序(.NET 4,C#,实体框架,Unity)时,一切正常,但是我创建了一个独立的控制台应用程序,将从任务计划程序运行以导入供稿。 我几乎要放弃,进行肮脏的黑客攻击,并编写脚本来调用网页,而不是使用控制台应用程序,但是我认为我至少会尝试理解为什么它首先无法正常工作。
我对Entity Framework和Unity都是陌生的,所以请多多包涵,并让我知道是否遗漏了任何重要信息。
这是我得到的错误:
Resolution of the dependency failed, type = "MyNamespace.Domain.Template.IRepository`2[MyNamespace.Domain.Employees.OrganisationalUnit,System.Guid]", name = "(none)".
Exception occurred while: while resolving.
Exception is: NullReferenceException - Object reference not set to an instance of an object.
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)
at MyNamespace.Infrastructure.FeedDefinition.GetOrganisationalUnit(String name, OrganisationalUnit parent) in C:\FeedDefinition.cs:line 552
这是控制台应用程序代码:
static void Main(string[] args)
{
if (args.Length > 0)
{
MyNamespace.Appliance.Configuration.Initialise.InitialiseContainer();
ImportFeedProcessor importFeedProcessor = new ImportFeedProcessor();
importFeedProcessor.Run(args[0]);
}
}
这是失败的地方:
IRepository<OrganisationalUnit, Guid> organisationalUnitRepository =
Context.Instance.Container.Resolve<IRepository<OrganisationalUnit, Guid>>();
如果有人可以帮助我了解发生了什么问题,我将非常感谢!
更新:
这是初始化类中的(重要)位:
public static void InitialiseContainer()
{
UnityContainer container = new UnityContainer();
// Use HttpContext for registering instances against for live
IContext context = HttpContextWrapper.Instance;
// Register the HttpContext as the default context to use
container.RegisterInstance<IContext>(HttpContextWrapper.Instance);
// repositories
container.RegisterType<IRepository<Employee, Guid>, EmployeeRepository>(
new UnityContextLifetimeManager(context),
new InjectionConstructor(true, "OrganisationalUnit.Parent.Parent"));
container.RegisterType<IRepository<OrganisationalUnit, Guid>, EntityFrameworkRepository<OrganisationalUnit, Guid>>(
new UnityContextLifetimeManager(context),
new InjectionConstructor("Parent.Parent"));
// Create and populate a new Unity container from configuration
Context.Instance.Container = container;
}
也许是HttpContext做到了吗?
谢谢,
安妮莉
您可以考虑的一种选择是创建两个不同的Initialise
类(我猜这是您的Unity bootstrapper类)。
您拥有的一个可以用于您的Web应用程序。
另一个应该不是特定于网络的。 删除对HttpContext
任何引用(在控制台应用程序中将不可用)和UnityContextLifetimeManager
(假定这也是HttpContext
特定的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.