Reputation: 20242
I'm trying to use Dependency
attribute with using RegisterInstance
. I've read that If I use RegisterInstance
I must use BuildUp
method on a instance. Unfortunately it doesn't work in my code. It doesn't resolve Alarm
property. When I use my code without RegisterInstance
everything is ok, but I need use RegisterInstance
. Do I miss something?
EDIT
var container = new UnityContainer();
container.RegisterType<IAlarm, Alarm>();
ICar car = new Car();
container.RegisterInstance<ICar>(car);
var carFromContainer = container.BuildUp<ICar>(container.Resolve<ICar>());
var alarm = carFromContainer.Alarm;
public interface ICar
{
IAlarm Alarm { get; set; }
}
public class Car : ICar
{
private IAlarm _alarm;
[Dependency]
public IAlarm Alarm
{
get { return _alarm; }
set { _alarm = value; }
}
}
public interface IAlarm
{
void Launch();
}
public class Alarm : IAlarm
{
public void Launch()
{
Console.WriteLine("Alarm !");
}
}
Old example
var container = new UnityContainer();
container.RegisterType<IAlarm, Alarm>();
ICar car = new Car();
container.RegisterInstance<ICar>(car);
//container.RegisterType<ICar, Car>();
var client = new Client(container);
var alarm = client.Car.Alarm;
client.Car.Alarm.Launch();
public class Client
{
public ICar Car { get; set; }
public Client(UnityContainer container)
{
//Car = container.Resolve<ICar>();
Car = container.BuildUp<ICar>(container.Resolve<ICar>());
}
}
public interface ICar
{
IAlarm Alarm { get; set; }
}
public class Car : ICar
{
private IAlarm _alarm;
[Dependency]
public IAlarm Alarm
{
get { return _alarm; }
set { _alarm = value; }
}
}
public interface IAlarm
{
void Launch();
}
public class Alarm : IAlarm
{
public void Launch()
{
Console.WriteLine("Alarm !");
}
}
Upvotes: 0
Views: 658
Reputation: 6806
I don't understand your sample code. You new up the Car
yourself and register it with the container. Then you tell the container to map IAlarm
to the implementing class Alarm
. Then you inject the container into your Client
which is something that is strongly disencouraged. DI containers should never be referenced outside the Composition root of your application. And then you (ab)use your container as a ServiceLocator (which is considered an anti-pattern in modern application architecture) to resolve ICar
and inject some value into a property.
I would recommend you re-think your design instead of looking for a solution to the technical issue you face.
UPDATE
Change your interface definition for ICar
and put the DependencyAttribute
there and it works.
But I cannot recommend that approach either. DI attributes should not polute your code.
Upvotes: 2