开发者

NHibernate and IoC IInterceptor

I have been trying to implement a solution similar to what Ayende posts in his MSDN article, Building a Desktop To-Do Application with NHibernate. Fortunately, Skooletz wrote a similar article that follows up what I am trying to accomplish with his 3 part blog post on NHibernate interceptor magic tricks (1, 2, 3). I am having trouble 开发者_如何转开发getting my POCO object's parametered constructor to be called by NHibernate when instantiating the object.

When I remove the protected parameterless constructor, NHibernate complains with an InvalidProxyTypeException: "The following types may not be used as proxies: YourNamespace.YourClass: type should have a visible (public or protected) no-argument constructor". If I then add in the protected default constructor, NHibernate no longer complains, but the dependency (in the overloaded constructor) is never called causing the application to barf with a NullReferenceException at runtime when the dependency is not satisfied.

public MyClass
{
    IRequiredDependency dependency;

    public MyClass(IRequiredDependency dependency)
    {
        this.dependency = dependency;
    }

    protected MyClass() {}
}

I just can't seem to get NHibernate to call the overloaded constructor. Any thoughts?


In the configuration of the IoC container, you have to declare your type with the dependency in addition to the dependency itself.

        container.RegisterType<IRequiredDependency, RequiredDependency>();
        container.RegisterType<MyClass, MyClass>();

I missed that little tidbit from Pablo's post (where he registers the Invoice class in addition to its dependency, IInvoiceTotalCalculator) as I am using Unity instead of Windsor.

One additional note: I found is that if you would like to have any other overloaded constructors, make them internal, leave the default constructor as protected and have only a single public constructor that contains your dependencies. This tidbit helped tighten up some of my API design for the classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜