-
Notifications
You must be signed in to change notification settings - Fork 25
InstanceRegistration
You can mark a field or property with the [Instance] attribute:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class InstanceAttribute : Attribute
{
public InstanceAttribute(Options options = Options.Default);
public Options Options { get; }
}Any field/property so marked will be registered as an instance for the type of the field/property.
How often the field will be accessed is an implementation detail, so the field/property must not change whilst the container is alive.
In order for an instance field or property to be exported by a module it must be public and static. For it to be inherited it can also be protected. Instance fields and properties in containers can be private and instance if desired.
The registration can be modified using the options parameter. See the documentation for more details.
This allows you to register the instance as more than just the type of the the field/property. In particular it is possible to register the instance as it's:
- Base classes
- Interfaces
- If it's an
IFactory<T>or anIAsyncFactory<T>, asT, as well as to registerT's base classes, interfaces, and factories etc.
By default all instances can be decorated. This can be opted out of by applying Options.DoNotDecorate.
Instance fields and properties will not be disposed by StrongInject. This is necessary so that modules containing instance fields and properties can be shared among multiple containers.
However if they are decorated, the decorators will be disposed. If the decorator chooses to delegate disposal to the underlying instance, this means the instance property will be disposed.
For that reason it's best to use the Options.DoNotDecorate parameter on disposable instances.
using StrongInject;
using System;
public class A { }
public class B : IDisposable { public void Dispose() { } }
public class C { public C(A a, B b) { } }
public class Module
{
[Instance(Options.DoNotDecorate)] public static readonly B _b = new B(); // Must be public and static. `Options.DoNotDecorate` is best practice as `B` is disposable.
}
[Register(typeof(C))]
[RegisterModule(typeof(Module))]
public partial class Container : IContainer<C>
{
[Instance] private readonly A _a; // Can be private and instance.
public Container(A a) => _a = a;
}