Dependency injection with NHibernate objects

前端 未结 3 858
北海茫月
北海茫月 2020-12-05 16:08

I am wondering how to tell NHibernate to resolve dependencies on my POCO domain objects.

I figured out that methods like CalculateOrderTax should be in the Domain ob

相关标签:
3条回答
  • 2020-12-05 16:54

    As no-one seems to be able to answer your question at the moment I thought I'd suggest restructuring your code to remove the need for the Order to calculate it's own tax.

    You could delegate it to a OrderTaxService which takes an Order object and returns an OrderValue object or something along those lines.

    This will keep the logic in your domain but remove the need to attach it to your Order objects.

    0 讨论(0)
  • 2020-12-05 16:55

    I agree with Garry that you should remove service dependencies from your domain objects as much as possible. Sometimes it makes sense, such as encryption/decryption. In that case you can hide it in the infrastructure using interception or IUserType. I think the latter is favorable when you can use it. This article shows in detail how to do it. I am doing this and it works quite fine.

    0 讨论(0)
  • 2020-12-05 17:02

    I've been using interceptors for similar tasks:

    An interceptor that modifies loaded entities:

    public class MyInterceptor : EmptyInterceptor
    {
        public override bool OnLoad(object entity, object id, object[] state, string[] propertyNames, IType[] types)
        {
            return InjectDependencies(entity as MyEntity);
        }
    }
    

    Associate it with a session:

    nhSessionFactory.OpenSession(myInterceptor);
    

    I've also read somewhere that there would be better support for custom constructor injection in the upcoming 2.1 release but I can't seem to find the reference right now.

    0 讨论(0)
提交回复
热议问题