UnityContainer.Resolve() will instantiate classes that have not been explicitly registered by means of reflection, allowing this sort of thing:
using System;
using Microsoft.Practices.Unity;
namespace ConsoleApplication2
{
public class Foo
{
public void SayHello()
{
Console.WriteLine("Hello");
}
}
class Program
{
static void Main(string[] args)
{
var container = new UnityContainer();
var foo = container.Resolve<Foo>();
foo.SayHello();
}
}
}
My question is, it is possible to disable this behaviour if I want to, so that the class is not automatically resolved (with either an exception being raised, or a null being returned?)
It’s not built in, but you could write a container extension which would change this behavior. It would require two things – first off, a handler for the registering event that recording when a type was registered in the policy list, and second, a strategy that would check the “is registered” policy and throw if it’s not there.
Its fairly small & easy to do if you’re familiar with writing extensions. Unfortunately I don’t have the time to put one together right now, sorry.