An injectable (IInjectable
) is a type that will populate its [Inject]
attributed members (properties and fields) when IInjectable.Inject(DependencyResolver resolver)
is called. This is typically used for dependency injection.
InjectableGeneration
will generate a partial class that implements IInjectable
for every class that contains at least one [Inject]
attributed member. The generated IInjectable.Inject
implementation will automatically resolve dependencies and populate members.
You should never have to implement IInjectable
yourself, but you must manually call IInjectable.Inject(DependencyResolver resolver)
with the appropritate dependency resolver (e.g., ServiceLocator
).
- Add a reference to the
Uno.CodeGen
NuGet package in your project. - Add the
[Inject]
attribute to members (fields and properties) of a class that should be injected. Make sure the class is partial.public partial class MyViewModel { [Inject] IMyService MyService; [Inject("name")] IMyService MyNamedService; [Inject] Func<IMyService> MyLazyService; }
- Compile (this is important to generate the partial portion of the class).
- A partial class that implements
IInjectable
will be generated:partial class MyViewModel : IInjectable { void IInjectable.Inject(DependencyResolver resolver) { MyService = (IMyService)resolver(type: typeof(IMyService), name: null); MyNamedService = (IMyService)resolver(type: typeof(IMyService), name: "name"); MyLazyService = () => (IMyService)resolver(type: typeof(IMyService), name: null); } }
- Inject a dependency resolver to initialize
[Inject]
attributed members:if (myViewModel is IInjectable injectable) { injectable.Inject(resolver: (type, name) => serviceLocator.GetInstance(type, name)); }
- All
[Inject]
attributed members should now be populated with the appropriate dependencies.