NibblyPig
NibblyPig

Reputation: 52942

Is there a workaround for dependency injection in a class library?

I have a class library that internally I have structured to use dependency injection (ninject). It's used by a variety of projects; MVC, windows services, REST apis etc.

I simply have a class like so:

public class KittenInvestigator
{
   [Inject]
   public IKittenDetectorDevice KittenDetectorDevice { get; set; }

   ...
}

Googling the issue to death I have found it to be impossible to initialise ninject in a class library as there is no 'startup' method or hook.

I'm looking for a workaround. There are tons of posts about the issue but I can't find any solutions or workarounds. Any ideas?

Some things I have considered:

Upvotes: 0

Views: 174

Answers (2)

BatteryBackupUnit
BatteryBackupUnit

Reputation: 13233

You could use Fody.ModuleInit to bootstrap the library automatically when its assembly is loaded. But i would not recommend it and instead do either of:

  • go the explicit way as described by Mark Seeman (and to which Steven already has provided a link as a comment to your post: DI friendly library
  • After carefully weighing the advantages and disadvantages opt to use ninject modules and use Dynamic Module Loading or something similar but custom.

Upvotes: 0

VidasV
VidasV

Reputation: 4895

You could have a startup method, create a static class called bootstrapper and do the composition of your DI container in the static constructor.

Upvotes: 1

Related Questions