Skip to content

Commit

Permalink
Merge pull request #62 from tsgcpp/feature/fix_to_use_AsTransient
Browse files Browse the repository at this point in the history
Fix to use "AsTransient" if InstanceLifetime is Transient
  • Loading branch information
neuecc authored Jun 18, 2021
2 parents e064160 + a122b89 commit 2d5d411
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,25 +39,25 @@ public void AddSingleton(Type type)

public void Add(Type type, InstanceLifetime lifetime)
{
if (lifetime == InstanceLifetime.Scoped)
{
builder.Bind(type).AsCached();
}
else
{
builder.Bind(type).AsSingle();
}
var binder = builder.Bind(type);
SetScope(binder, lifetime);
}

public void Add(Type serviceType, Type implementationType, InstanceLifetime lifetime)
{
if (lifetime == InstanceLifetime.Scoped)
var binder = builder.Bind(serviceType).To(implementationType);
SetScope(binder, lifetime);
}

private void SetScope(ScopeConcreteIdArgConditionCopyNonLazyBinder binder, InstanceLifetime lifetime)
{
if (lifetime == InstanceLifetime.Transient)
{
builder.Bind(serviceType).To(implementationType).AsCached();
binder.AsTransient();
}
else
{
builder.Bind(serviceType).To(implementationType).AsSingle();
binder.AsCached();
}
}
}
Expand Down
36 changes: 36 additions & 0 deletions src/MessagePipe.Unity/Assets/Tests/ZenjectTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,42 @@ public void InstanceLifetimeTransientToTransientInBindMessagePipe()
Assert.AreEqual(InstanceLifetime.Transient, option.RequestHandlerLifetime);
}

[Test]
public void BindMessageBrokerWithLifetimeScoped()
{
var resolver = TestHelper.BuildZenject((options, builder) =>
{
options.InstanceLifetime = InstanceLifetime.Scoped;
builder.BindMessageBroker<int>(options);
});

var pub1 = resolver.Resolve<IPublisher<int>>();
var pub2 = resolver.Resolve<IPublisher<int>>();
var sub1 = resolver.Resolve<ISubscriber<int>>();
var sub2 = resolver.Resolve<ISubscriber<int>>();

Assert.AreEqual(pub1, pub2);
Assert.AreEqual(sub1, sub2);
}

[Test]
public void BindMessageBrokerWithLifetimeTransient()
{
var resolver = TestHelper.BuildZenject((options, builder) =>
{
options.InstanceLifetime = InstanceLifetime.Transient;
builder.BindMessageBroker<int>(options);
});

var pub1 = resolver.Resolve<IPublisher<int>>();
var pub2 = resolver.Resolve<IPublisher<int>>();
var sub1 = resolver.Resolve<ISubscriber<int>>();
var sub2 = resolver.Resolve<ISubscriber<int>>();

Assert.AreNotEqual(pub1, pub2);
Assert.AreNotEqual(sub1, sub2);
}

public class IntClass
{
public int Value { get; set; }
Expand Down

0 comments on commit 2d5d411

Please sign in to comment.