Dependency Injection by code

Posts   
 
    
Barry
User
Posts: 232
Joined: 17-Aug-2005
# Posted on: 20-May-2008 04:14:35   

I''m trying to implement entity auditor, and according from the documentation, the auditor value can be assigned by injection in real time. However, the dependency injection is setup by application config file, can I setup it by coding alternatively?!

Walaa avatar
Walaa
Support Team
Posts: 14950
Joined: 21-Aug-2005
# Posted on: 20-May-2008 08:40:20   

As far as I know Dependency Injection is about, not using code, i.e. it's about using the config file, to inject properties with instance of a specific type.

If you want to set the AuditorToUse property of an entity in code then you have 2 options:

manual wrote:

1- Setting the AuditorToUse property of an entity object manually. This is straight forward, but error prone: if you forget to set an auditor, auditing isn't performed. Also, entities fetched in bulk into a collection are created using the factories so you have to alter these as well. You could opt for overriding OnInitializing in an entity to add the creation of the Auditor class.

2- By overriding the Entity method CreateAuditor. This is a protected virtual (Protected Overridable) method which by default returns null / Nothing. You can override this method in a partial class or user code region of the Entity class to create the Auditor to use for the entity. The LLBLGen Pro runtime framework will take care of calling the method.

Barry
User
Posts: 232
Joined: 17-Aug-2005
# Posted on: 20-May-2008 09:07:40   

I want to create an interface to let users to enable or disable auditing feature and let them to select which type of entity should save the audit data. Because my application has lots of entity, and users only want to keep audit data for some of them. Therefore, I'm thinking to use injection feature and setup it by code.

Option 2 seems to be the more suitable ways to go, but I'm afraid it would hit performance a lots if I place some logic in CreateAuditor method to check if it's required to assign Auditor to a specific type of entity. disappointed

Walaa avatar
Walaa
Support Team
Posts: 14950
Joined: 21-Aug-2005
# Posted on: 20-May-2008 09:31:39   

You may write to an XML file for instance. And then in the CreateAuditor implementation, you may use reflection or something like Activator.CreateInstance() to create the needed Auditor.

Which is by the way pretty much the same thing done by DI.