Unity/VContainer
유니티를 위한 DI 프레임워크 VContainer, Register Plain C# Type
VR하는소년
2023. 3. 12. 09:00
Register를 사용하기 위해서는 다양한 방법이 존재합니다
class ServiceA : IServiceA, IInputPort, IDisposable { /* ... */ }
Register Concrete Type
builder.Register<ServiceA>(Lifetime.Singleton);
위 코드는 다음처럼 풀어낼 수 있습니다
class ClassA
{
public ClassA(ServiceA serviceA) { /* ... */ }
}
Register as Interface
builder.Register<IServiceA, ServiceA>();
위 코드는 다음처럼 풀어낼 수 있습니다
class ClassA
{
public ClassA(IServiceA serviceA) { /* ... */ }
}
Register as multiple Interface
builder.Register<ServiceA>(Lifetime.Singleton)
.As<IServiceA, IInputPort>();
위 코드는 다음처럼 풀어낼 수 있습니다
class ClassA
{
public ClassA(IServiceA serviceA) { /* ... */ }
}
class ClassB
{
public ClassB(IInputPort inputPort) { /* ... */ }
}
Register all implemented interfaces automatically
builder.Register<ServiceA>(Lifetime.Singleton)
.AsImplementedInterfaces();
위 코드는 다음처럼 풀어낼 수 있습니다
class ClassA
{
public ClassA(IServiceA serviceA) { /* ... */ }
}
class ClassB
{
public ClassB(IInputPort inputPort) { /* ... */ }
}
Register all implemented interfaces and concrete type
builder.Register<ServiceA>(Lifetime.Singleton)
.AsImplementedInterfaces()
.AsSelf();
위 코드는 다음처럼 풀어낼 수 있습니다
class ClassA
{
public ClassA(IServiceA serviceA) { /* ... */ }
}
class ClassB
{
public ClassB(IInputPort inputPort) { /* ... */ }
}
class ClassB
{
public ClassB(ServiceA serviceA) { /* ... */ }
}
Register instance
// ...
var obj = new ServiceA();
// ...
builder.RegisterInstance(obj);
RegisterIntance는 항상 Singleton lifetime 가지고 있으므로 굳이 Singleton lifetime를 매개인자로 쓸 필요 없습니다!
위 코드는 다음처럼 풀어낼 수 있습니다
class ClassA
{
public ClassA(ServiceA serviceA) { /* ... */ }
}
(미완...)
Instances registered with RegisterInstance are not managed by the container.
- Dispose will not be executed automatically.
- Method Injection will not be executed automatically
If you want the container to manage the created instances, consider using the following instead
Register instance as interface
Use As* declarations.
builder.RegisterInstance<IInputPort>(serviceA);
builder.RegisterInstance(serviceA)
.As<IServiceA, IInputPort>();
builder.RegisterInstance()
.AsImplementedInterfaces();
Register type-specific parameters
If the types are not unique, but you have a dependency you want to inject at startup, you can use the following:
builder.Register<SomeService>(Lifetime.Singleton)
.WithParameter<string>("http://example.com");
Or, you can name a paramter with a key.
builder.Register<SomeService>(Lifetime.Singleton)
.WithParameter("url", "http://example.com");
It can resolve like this:
class SomeService
{
public SomeService(string url) { /* ... */ }
}
This Register only works when being injected into SomeService.
class OtherClass
{
// ! Error
public OtherClass(string hogehoge) { /* ... */ }
}