0

在我的项目中,我使用的是 Autofac。以前它工作正常。现在我在 Autofac 中添加了一些新代码,它给了我“创建委托不能返回 null ”错误。

我所做的更改如下

 builder.Register<Rep>(c => {
                                      /*Get Session and LoginId*/

                               return session.CreateQuery(@"from Rep where LoginId='" +
                                                   LoginId+ "'").List<Rep>().
                                                   FirstOrDefault() ?? new Rep();
                            });
 builder.Register<TestPermissionHelper>();

现在在我正在解决Global.asax的方法中。Applicaiton_PostAuthenticate()TestPermissionHelper

有趣的是,当我点击登录页面时,它给了我错误,否则它工作正常。

我知道很难从这个小代码中理解整个画面。如果有人至少可以告诉我,一般来说这种错误的可能原因是什么,那就太好了。

谢谢

注意:如果有帮助,我也会给出错误的堆栈跟踪

    Stack trace:    at Autofac.Component.Activation.DelegateActivator.ActivateInstance(IContext context, IEnumerable`1 parameters)
   at Autofac.Component.Registration.ResolveInstance(IContext context, IEnumerable`1 parameters, IDisposer disposer, Boolean& newInstance)
   at Autofac.Context.TryResolve(Service service, Object& instance, IEnumerable`1 parameters)
   at Autofac.Context.Resolve(Service service, IEnumerable`1 parameters)
   at Autofac.Context.Resolve(Type serviceType, IEnumerable`1 parameters)
   at Autofac.Component.Activation.AutowiringParameter.<>c__DisplayClass2.<CanSupplyValue>b__0()
   at Autofac.Component.Activation.DirectConstructorInvoker.<InvokeConstructor>b__0(Func`1 pa)
   at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at Autofac.Component.Activation.DirectConstructorInvoker.InvokeConstructor(IContext context, IEnumerable`1 parameters, ConstructorInfo ci, Func`1[] args)
   at Autofac.Component.Activation.ReflectionActivator.ConstructInstance(ConstructorInfo ci, IContext context, IEnumerable`1 parameters, Func`1[] parameterAccessors)
   at Autofac.Component.Activation.ReflectionActivator.ActivateInstance(IContext context, IEnumerable`1 parameters)
   at Autofac.Component.Registration.ResolveInstance(IContext context, IEnumerable`1 parameters, IDisposer disposer, Boolean& newInstance)
   at Autofac.Context.TryResolve(Service service, Object& instance, IEnumerable`1 parameters)
   at Autofac.Context.Resolve(Service service, IEnumerable`1 parameters)
   at Autofac.Context.Resolve(Type serviceType, IEnumerable`1 parameters)
   at Autofac.Context.Resolve[TService](IEnumerable`1 parameters)
   at Autofac.Context.Resolve[TService](Parameter[] parameters)
   at Autofac.Container.Resolve[TService](Parameter[] parameters)
4

2 回答 2

0

null您的代码似乎足够好,除非发生错误,否则我看不到委托注册将如何返回。

我建议编写一些单元测试,尝试使用注册TestPermissionHelper中的各种返回值(包括 null)进行解析Rep。希望您能够重现错误并隔离错误发生的条件。

于 2010-05-11T18:47:53.557 回答
0

问题的根本原因似乎不在 Autofac 中。如果 Rep 表没有登录 id 的条目,则创建一个新的 Rep 对象。如果在其他组件中用作依赖项,则需要确保它们不引用 Rep 对象的非实例化引用属性。

于 2010-05-12T12:27:19.933 回答