modesttree / Zenject

Dependency Injection Framework for Unity3D
MIT License
2.48k stars 272 forks source link

Suggestion: Add optional identifier to BindInterfacesTo<T> #103

Open sbergen opened 4 years ago

sbergen commented 4 years ago

Context

Using private identifiers is a nice way to make some interfaces of a single object globally available, while restricting other interfaces for specific classes. Consider the following example:

private class TestClass
{
    public TestClass(IComparable foo)
    {}
}

[Test]
public void FromResolveWithId()
{
    var container = new DiContainer();
    var id = new object();

    container
        .Bind(typeof(int).GetInterfaces())
        .WithId(id)
        .To<int>()
        .AsSingle();

    // Make IComparable only available to TestClass
    container
        .Bind<IComparable>()
        .FromResolve(id)
        .WhenInjectedInto<TestClass>();

    container
        .Bind<TestClass>()
        .AsSingle();

    // Make IFormattable available for everyone
    container
        .Bind<IFormattable>()
        .FromResolve(id);

    Assert.NotNull(container.Resolve<TestClass>());
    Assert.NotNull(container.Resolve<IFormattable>());
}

Problem

As BindInterfacesTo<T> already does the To binding, this causes WithId to no longer be available. This means that BindInterfacesTo<T> can't be used in this scenario.

Solution

Add the optional parameter object identifier = null to BindInterfacesTo<T> to simplify the syntax from

container
    .Bind(typeof(T).GetInterfaces())
    .WithId(id)
    .To<T>()

to

container
    .BindInterfacesTo<T>(id)
Mathijs-Bakker commented 4 years ago

Good one!