Using Unity DI with a Console Application

别等时光非礼了梦想. 提交于 2019-12-04 11:05:31
user2864740

Unity only supplies dependencies for components obtained via Resolve or while resolving sub-dependencies. The "root" component or components must be obtained from the container manually.

Using new Program would not automatically provide the dependencies because it bypasses the Unity container.

static class ProgramEntry
{
    static void Main(string[] args)
    {
        var unity = CreateUnityContainerAndRegisterComponents();
        // Explicitly Resolve the "root" component or components
        var program = unity.Resolve<Program>();
        program.Run();
    }
}

public class Program
{
    readonly Ix _x;

    // These dependencies will be automatically resolved
    // (and in this case supplied to the constructor)
    public Program(IMapper mapper, Ix x)
    {
        // Use dependencies
        mapper.RegisterMappings();

        // Assign any relevant properties, etc.
        _x = x;
    }

    // Do actual work here
    public void Run() {
        _x.DoStuff();
    }
}

I prefer code-based registration for most tasks.

  • I recommend not using attributes, although they 'will work' if following the Resolve pattern above. The "root" objects must be manually resolved.

    The problem with attributes is these add a dependencies on Unity - so much for "inverting"!

    Constructor Injection (as shown) is automatic/default. See Setter / property injection in Unity without attributes if Property Injection is preferred.

  • I would probably resolve a Factory (or Func<UoW>) to create a UoW and supply it down the call-stack context (ie. pass it to methods) when applicable. The application may have many different UoWs during a single run. In this case you may also be interested in creating scopes.

  • I would also probably use a factory to create a pre-configured IMapper object when it is resolved instead of using RegisterMappings afterwards.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!