standards-c-sharp

Register components with DI using Attributes

Simple registrations

[RegisterSingleton]  // equivalent to ContainerControlledLifetimeManager – one instance shared for the lifetime of the application
[RegisterPerRequest] // equivalent to HttpContextLifetimeManager – one instance created and shared for each web request
[RegisterTransient]  // equivalent to TransientLifetimeManager – one instance created each time requested from the container, never shared

Don’t

container.RegisterType<MyClass, MyInterface>(new ContainerControlledLifetimeManager());

Do

[RegisterSingleton]
public class MyClass : MyInterface 
{
  ...
}

Mocking

Don’t

if (!Configuration.IsMock)
{
  container.RegisterType<IMyService, MyService>();
}
else
{
  container.RegisterType<IMyService, MyServiceMock>();
}

Do

[RegisterTransient(MockImplementation = typeof(MyServiceMock))] 
public class MyService : IMyService
{
}