Questions tagged [unity-container]

The Unity Application Block (i.e. Unity) is a lightweight, extensible dependency injection container for .NET with support for interception. DO NOT USE THIS TAG TO REFER TO THE UNITY GAME ENGINE! Use unity-game-engine instead (https://stackoverflow.com/tags/unity-game-engine/info)!

The Unity Application Block (i.e. Unity Container) is a lightweight, extensible dependency injection container for .NET. It also supports interception.

Unity targets both .NET CLR and Silverlight.

Installing Unity can most easily be done using its NuGet package:

Install-Package Unity

More information at:

Hello world in c#

interface IMessageWriter 
{
    void WriteMessage(string message);
}

class ConsoleWriter : IMessageWriter 
{
    public void WriteMessage(string message) 
    { 
        Console.WriteLine(message); 
    }
}

class HelloWorldService 
{
    private readonly IMessageWriter _writer;

    public HelloWorldService(IMessageWriter writer) 
    {
       _writer = writer;
    }

    public void Go() 
    {
       _writer.WriteMessage("Hello World!");
    }
}

using (var container = new UnityContainer()) 
{        
    container.RegisterType<IMessageWriter, ConsoleWriter>();

    var helloWorldService = container.Resolve<HelloWorldService>();

    helloWorldService.Go();    
}
3920 questions
22
votes
3 answers

Unity not using the default constructor of the class

I have this class : public class Repo { public Repo() : this(ConfigurationManager.AppSettings["identity"], ConfigurationManager.AppSettings["password"]) { } public Repo(string identity,string password) { //Initialize…
Attilah
  • 17,632
  • 38
  • 139
  • 202
21
votes
6 answers

How to Inject Log4Net ILog implementations using Unity 2.0

Ultimately this has to do with setting up log4Net but generically the problem is not logging specific. Generically what I am trying to figure out is how to do, in Microsoft Unity 2.0, something equivalent to what one gets with the…
21
votes
2 answers

Dependency Injection Unity - Conditional Resolving

Conditional resolving is the last thing I don't understand at the moment. Lets say we have an interface IAuthenticate: public interface IAuthenticate{ bool Login(string user, string pass); } Now I have two types of authentication. Twitter…
sensei
  • 7,044
  • 10
  • 57
  • 125
21
votes
4 answers

Unity IoC does not inject dependency into Web API Controller

I'm very new to using Unity, but my problem is that whenever I call my web service, I get an exception stating that "Make sure that the controller has a parameterless public constructor" I've followed multiple tutorials and I still get the same…
Carlos Rodriguez
  • 2,190
  • 2
  • 18
  • 29
21
votes
4 answers

How to pass Owin context to a Repo being injected into Api controller

I've got a MVC WebApi owin (soft hosted) project, that uses Unity for resolving controller dependencies which look like this public class PacientaiController : ODataController { private readonly IEntityRepo repo; …
Marty
  • 3,485
  • 8
  • 38
  • 69
21
votes
1 answer

Should I use OwinContext's Environment to hold application specific data per request

I need a way to store a logging object per request. With HttpContext I would add this to the items Dictionary. I don't want to bring HttpContext into this if I can help it. The below code is what I propose for a Unity LifeTimeManager that will store…
codetoast
  • 293
  • 1
  • 2
  • 9
21
votes
3 answers

How do I inject a connection string into an instance of IDbContextFactory?

I'm using Entity Framework 5 with Code First Migrations. I have a DataStore class which derives from DbContext: public class DataStore : DbContext, IDataStore { public int UserID { get; private set; } public DataStore(int userId, string…
21
votes
5 answers

The type String cannot be constructed

I'm using Web.api and Unity and I am getting the following error when trying to open the default "help" area: [InvalidOperationException: The type String cannot be constructed. You must configure the container to supply this…
20
votes
4 answers

Auto-register all interfaces with Unity

Using Unity, I'd like to automatically register all interface/class combinations in an assembly based on the following convention: INameOfObject > NameOfObject StructureMap does that when the default conventions are enabled. I wrote the following…
David
  • 3,736
  • 8
  • 33
  • 52
20
votes
3 answers

Dependency Injection composition root and decorator pattern

I'm getting StackoverflowException's in my implementation of the decorator pattern when using dependency injection. I think it is because I'm "missing" something from my understanding of DI/IoC. For example, I currently have CustomerService and…
20
votes
2 answers

Unity IOC Buildup vs Resolve?

I was wondering when do I use buildup and when do I use resolve, when using the Unity IOC. And when do I call teardown? Thanks
Joshscorp
  • 1,832
  • 4
  • 22
  • 42
20
votes
5 answers

Register null as instance in Unity container

I have a repository class with optional dependency: class MyRepository : BaseRepository, IMyRepository { public MyRepository(IDataContext dataContext, ICacheProvider cacheProvider = null) : base(dataContext, cacheProvider) {} //…
v0id
  • 346
  • 5
  • 16
19
votes
3 answers

Resolve instance with multiple constructors using unity

I'd like to create an instance of a class using unity where the class has two constructors with the same number of parameters. Here is the instantiation: _unityContainer.Resolve(new ParameterOverride("gradeTypeStringFromXmlFile",…
FatAlbert
  • 4,890
  • 6
  • 22
  • 34
19
votes
3 answers

Can a unity container pass a reference of itself as a constructor parameter?

Is there a way for a unity container to pass itself to an object? i.e.: public class Something { public Something(IUnityContainer container) { ... } }
Jay Allard
  • 938
  • 6
  • 12
19
votes
4 answers

Unity auto-factory with params

I'm trying to figure out the correct way to inject an auto-factory which takes params, or even if this is possible with Unity. For example I know I can do this: public class TestLog { private Func logFactory; public…
TheCodeKing
  • 19,064
  • 3
  • 47
  • 70