user7128918
user7128918

Reputation:

Dependency injection at runtime using Unity

DataAccessLayer.cs in DataAccess project:

public class DataAccessLayer : IDataAccessLayer
{
    public void Bar()
    {
        // Implementation
    }
}

IDataAccessLayer.cs in DataAccess.Contracts project:

public interface IDataAccessLayer
{
    void Bar();
}

MyClass.cs in Main project (Console Application):

public class MyClass
{
    public IDataAccessLayer Dal { get; set; } /// Her I want to inject dependency at runtime
}

I want to inject the dependency in MyClass.Dal property directly at runtime. I use Unity and a configuration file in main project :

<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <container>
    <register type="DataAccess.Contracts.IDataAccessLayer, DataAccess.Contracts" mapTo="DataAccess.DataAccessLayer, DataAccess"/>
  </container>
</unity>

I just install Unity from Nuget in my main project.

If I do var instance = new MyClass(); in main method of my main project, instance.Dal is null.

How to inject the value of Dal at runtime ?

Update 1 :

Ideally I would like all the dependencies of my main project to be resolved via a script in my main method or directly through the configuration. Is it possible ?

Upvotes: 0

Views: 934

Answers (2)

ctor
ctor

Reputation: 875

you can use constructor injection to inject dependencies in following way-

public class MyClass
{
    public MyClass (IDataAccessLayer dal)
    {
        this.Dal = dal;
    }

    public IDataAccessLayer Dal { get; set; } 
}

To resolve the dependencies, you have to first load these into container from config.

IUnityContainer container = new UnityContainer();
container.LoadConfiguration();
MyClass myClass = container.Resolve<MyClass>(); -- instance of IDataAccessLayer will be injected in myClass

Refer Dependency Injection with Unity to learn more about registering, resolving and injecting dependencies.

Upvotes: 0

CodingYoshi
CodingYoshi

Reputation: 27009

I suggest you use constructor injection instead because it makes the dependencies very clear:

public class MyClass
{
    public MyClass(IDataAccessLayer dal)
    {
        this.Dal = dal;
    }
    public IDataAccessLayer Dal { get; set; } 
}

Or use DependencyAttribute on your property for property injection:

[DependencyAttribute]
public IDataAccessLayer Dal { get; set; } 

Please read What does Unity Do for more details.

Upvotes: 2

Related Questions