# Dependency Injection Notes
## General Notes
The general idea is to create your dependencies ahead of time so that you can pass them along to the classes, objects, etc. that need them. This lets you create real services or fake (mocked) ones that simulate the real deal.
## Conventions
A dependency will generally end in "-Service":
```csharp
var myService = Factory.Create<UsefulService>();
```
That dependency can then be passed along to users:
```csharp
var viewModel = new InterestingViewModel(myService);
```
## Information
In doing so, you negate the need for each user to have to create their own version of the dependency, or need to make dependency a singleton or static. Further, you allow easier testing by being able to mock the service.
```c#
// Put your factory somewhere accessible
public static IHost ShredVaultSolutionFactory
// ***************************************************************
// Create the builder before adding any services
HostApplicationBuilder builder = Host.CreateApplicationBuilder();
// Basic example of a singleton service being added to the builder
builder.Services.AddSingleton<IUserState, UserState>();
// Basic example of a transient service being added,
// which means you'll get a new instance every time you ask for one
builder.Services.AddTransient<PINModel>();
// You can add a 'keyed' service in order to be able to get a
// specific instance back again later, such as when adding more
// than one of a given type. This also shows how to set up
// initialization when adding a service to the builder
builder.Services.AddKeyedSingleton<IUSBCameraService, IUSBCameraService>(KioskDevice.CameraOne, (sp, key) =>
{
var service = new USBCameraService(KioskDevice.CameraOne);
service.Initialize();
return service;
});
// Build() initializes the services in the factory
_shredVaultSolutionFactory = builder.Build();
```
## Things To Avoid
There seems to be a possibility of setting up services too early, e.g. in the context of a WPF application, in `App.xaml.cs`:
```c#
App()
{
// Building services here using HostApplicationBuilder is a
// potential FileNotFoundException or FileLoadException on startup
}
```
#c_sharp