Freigeben über


The one where Toby finds a dependency injection container

Toby is less than happy. Due to some unforeseen circumstances, he recently lost all the code he'd been working on for the EDM project. For some unknown reason, he'd never bothered to setup a source control server and vows to not make the same mistake twice.

Desperate to kick-start his excitement on the project again, he remembers coming to the conclusion that he'd need some sort of dependency injection container. Although initially he was contemplating using CAB, he realised that what he really wanted was just part of the container functionality from WorkItem. After a bit of searching, he found that the current version of ObjectBuilder ships with the sample container from Codeplex. Deciding that it would be nice to shift gears for a while, he fires up Visual Studio and starts writing some tests.

 [TestFixture]      
public class Injection       
{       
    [Test]       
    public void CanInjectService()       
    {       
        DependencyContainer container = new DependencyContainer();       
        container.RegisterSingletonInstance<IUserService>(new UserService());         Project newProject = container.Get<Project>();
        Assert.NotNull(newProject.UserService);      
        Assert.Equal("casper", newProject.UserService.CurrentUser);       
    } 
    [Test]      
    public void InjectedServiceIsReallyTheSameOneWeThinkItIs()       
    {       
        DependencyContainer container = new DependencyContainer();       
        UserService userService = new UserService();       
        container.RegisterSingletonInstance<IUserService>(userService);       
        Project newProject = container.Get<Project>(); 
        userService.CurrentUser = "B-rad";    
        Assert.Equal("B-rad", newProject.UserService.CurrentUser);      
    } 
    class Project      
    {       
        [Dependency]       
        public IUserService UserService       
        {       
            get { return userService; }       
            set { userService = value; }       
        } 
        private IUserService userService;      
    } 
    interface IUserService      
    {       
        string CurrentUser { get; }       
    }
    class UserService : IUserService      
    {       
        public string CurrentUser       
        {       
            get { return currentUser; }       
            set { currentUser = value; }       
        } 
        private string currentUser = "casper";      
    }       
}

So, nothing too fancy, but the start of how we can separate concerns in the project. And Toby has learned his lesson, and will soon start posting code on Codeplex.