Last active
July 30, 2019 10:02
-
-
Save adamjasinski/8ce73d2d9fc9b7c8fffc6386bb0094c5 to your computer and use it in GitHub Desktop.
StructureMap policies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Xunit; | |
using StructureMap; | |
using StructureMap.Pipeline; | |
using System.Linq; | |
namespace StructureMapDemo | |
{ | |
public class UnitTest1 | |
{ | |
[Fact] | |
public void Test1() | |
{ | |
var container = new Container(x => | |
{ | |
x.For<IRepository>().Add<MyRepository>() | |
.Named("RepoA").Ctor<string>("prefix").Is("RepoA"); | |
x.Policies.Add(new InjectedRepositoryPolicy()); | |
}); | |
var inst1 = container.GetInstance<ControllerA>(); | |
Assert.IsType<MyRepository>(inst1.Repository); | |
Assert.Equal("RepoA", inst1.Repository.Prefix); | |
var inst2 = container.GetInstance<ControllerA>(); | |
Assert.IsType<MyRepository>(inst2.Repository); | |
Assert.Equal("RepoA", inst2.Repository.Prefix); | |
} | |
} | |
public class InjectedRepositoryPolicy : ConfiguredInstancePolicy | |
{ | |
protected override void apply(Type pluginType, IConfiguredInstance instance) | |
{ | |
System.Diagnostics.Debug.WriteLine($"Plugin type: {pluginType.FullName}, Instance name: {instance.Name}"); | |
var parameter = instance.Constructor.GetParameters().FirstOrDefault(x => x.ParameterType == typeof(IRepository)); | |
if (parameter != null) | |
{ | |
var repoKey = (pluginType == typeof(ControllerA)) ? "RepoA" : "RepoB"; | |
var repoInstance = new ReferencedInstance(repoKey); | |
instance.Dependencies.AddForConstructorParameter(parameter, repoInstance); | |
} | |
// instance.Constructor.GetParameters() | |
// .Where(p => p.ParameterType == typeof(IRepository)) | |
// .Each() | |
} | |
} | |
public interface IRepository | |
{ | |
string Prefix { get; } | |
} | |
public class MyRepository : IRepository | |
{ | |
public MyRepository(string prefix){ | |
Prefix = prefix; | |
} | |
public string Prefix { get; } | |
} | |
public class ControllerA | |
{ | |
public ControllerA(IRepository repository) | |
{ | |
Repository = repository; | |
} | |
public IRepository Repository { get; } | |
} | |
public class ControllerB | |
{ | |
public ControllerB(IRepository repository) | |
{ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A few thoughts:
Type checking
This would grow into a long switch if we just referenced each individual Controller here. Wonder if this works if we had a "base" interface for each payment type?
P24RefundsPutController
already has a base class, so we can't use another base class.Tests
Should just add one for Controller B