### Example Settings Class Source: https://structuremap.github.io/registration/on-missing-family-policies A sample class representing application settings. ```csharp public class SomeSettings { public string ThisDirectory { get; set; } public string ThatDirectory { get; set; } } ``` -------------------------------- ### Try Get Instance by Type and Name Source: https://structuremap.github.io/resolving/try-geting-an-optional-service-by-plugin-type-and-name This example demonstrates how to use `IContainer.TryGetInstance(Type pluginType, string name)` to retrieve an instance of a service by its `Type` and a specific name. This is useful when the generic type is not known at compile time. ```APIDOC ## Try Get Instance by Type and Name ### Description Retrieves an optional service instance using its `Type` and a specific name. Returns null if no service matches the criteria. ### Method `IContainer.TryGetInstance(Type pluginType, string name)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp Type ruleType = typeof(Rule); var instance = _container.TryGetInstance(ruleType, "Orange"); ``` ### Response #### Success Response (Instance Found) - **instance** (object) - The retrieved service instance. #### Success Response (Instance Not Found) - **instance** (null) - Returns null if no service with the specified type and name is registered. #### Response Example ```csharp // When found instance.ShouldBeOfType(typeof(ColorRule)); // When not found var notFoundInstance = _container.TryGetInstance(typeof(Rule), "NonExistentService"); notFoundInstance.ShouldBeNull(); ``` ``` -------------------------------- ### Install StructureMap via NuGet Source: https://structuremap.github.io/get-structuremap Use this command in the Package Manager Console to install the main StructureMap package. ```powershell PM> Install-Package StructureMap ``` -------------------------------- ### Constructor and Setter Injection Example Source: https://structuremap.github.io/software-design-concepts Demonstrates Dependency Injection using constructor injection and setter injection. Ensure the dependent interfaces and classes are properly configured for resolution. ```csharp public interface IDatabase { } public class DatabaseUser { // Using Constructor Injection public DatabaseUser(IDatabase database) { } } public class OtherDatabaseUser { // Setter Injection public IDatabase Database { get; set; } } ``` -------------------------------- ### Configure Container for WhatDoIHave() Example Source: https://structuremap.github.io/diagnostics/whatdoihave This snippet demonstrates configuring a StructureMap container with various registrations, which can then be reported on using WhatDoIHave(). ```csharp var container = new Container(x => { x.For().Use().Named("The Hemi"); x.For().Add().Singleton().Named("V8"); x.For().Add().AlwaysUnique(); x.For().Add().LifecycleIs(); x.For().Add(() => new Rotary()).Named("Rotary"); x.For().Add(c => c.GetInstance()); x.For().Add(new InlineFour()); x.For().UseIfNone(); x.For().MissingNamedInstanceIs.ConstructedBy(c => new NamedEngine(c.RequestedName)); }); ``` -------------------------------- ### Get Default Build Plan for an Instance Source: https://structuremap.github.io/diagnostics/build-plans Retrieve the textual build plan for the default instance of a plugin type. This helps visualize the construction process. ```csharp var container = Container.For(); var description = container.Model.For().Default .DescribeBuildPlan(); Debug.WriteLine(description); ``` -------------------------------- ### Include Registries in Container Setup Source: https://structuremap.github.io/registration/registry-dsl Direct a `Container` to use configurations from other `Registry` classes by calling `IncludeRegistry()`. ```csharp [Fact] public void include_a_registry() { var registry = new Registry(); registry.IncludeRegistry(); registry.IncludeRegistry(); registry.IncludeRegistry(); // build a container var container = new Container(registry); // verify the default implementation and total registered implementations container.GetInstance().ShouldBeOfType(); container.GetAllInstances().Count().ShouldBe(5); } ``` -------------------------------- ### Try Get Instance by Generic Type and Name Source: https://structuremap.github.io/resolving/try-geting-an-optional-service-by-plugin-type-and-name This example shows how to use `IContainer.TryGetInstance(name)` to retrieve an instance of a service by its generic type and a specific name. It asserts that an instance is returned when a service matching the criteria exists. ```APIDOC ## Try Get Instance by Generic Type and Name ### Description Retrieves an optional service instance using its generic type and a specific name. Returns null if no service matches the criteria. ### Method `IContainer.TryGetInstance(string name)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var instance = _container.TryGetInstance("Orange"); ``` ### Response #### Success Response (Instance Found) - **instance** (Rule) - The retrieved service instance. #### Success Response (Instance Not Found) - **instance** (null) - Returns null if no service with the specified type and name is registered. #### Response Example ```csharp // When found instance.ShouldBeOfType(typeof(ColorRule)); // When not found var notFoundInstance = _container.TryGetInstance("NonExistentService"); notFoundInstance.ShouldBeNull(); ``` ``` -------------------------------- ### Service Locator Example with StructureMap Source: https://structuremap.github.io/software-design-concepts Illustrates the Service Locator pattern where a container is used to resolve dependencies on demand. Favor Dependency Injection when possible, but Service Locator can be useful for advanced scenarios. ```csharp public class ThirdDatabaseUser { private IDatabase _database; public ThirdDatabaseUser(IContainer container) { // This is service location _database = container.GetInstance(); } } ``` -------------------------------- ### Define Classes for Widget and Service Source: https://structuremap.github.io/resolving/passing-arguments-at-runtime Defines sample classes `ColorWidget` and `GuyWithWidgetAndService` that will be used in subsequent examples. `ColorWidget` has a constructor that accepts a string color, and `GuyWithWidgetAndService` depends on `IWidget` and `IService`. ```csharp public class ColorWidget : IWidget { public string Color { get; set; } public ColorWidget(string color) { Color = color; } } public class GuyWithWidgetAndService { public IWidget Widget { get; set; } public IService Service { get; set; } public GuyWithWidgetAndService(IWidget widget, IService service) { Widget = widget; Service = service; } } ``` -------------------------------- ### StructureMap Configuration Exception Example Source: https://structuremap.github.io/diagnostics/validating-container-configuration This is an example of the exception StructureMap throws when it encounters errors during configuration validation. It summarizes all problems, including build errors and validation errors. ```text StructureMap.StructureMapConfigurationException StructureMap Failures: 1 Build/Configuration Failures and 0 Validation Errors Profile 'DEFAULT' ----------------------------------------------------------------------------------------------------- Build Error on Instance 'StructureMap.Testing.Diagnostics.NamedWidget' for PluginType StructureMap.Testing.Diagnostics.IWidget Unable to create a build plan for concrete type StructureMap.Testing.Diagnostics.NamedWidget new NamedWidget(String name) ┗ String name = Required primitive dependency is not explicitly defined ``` -------------------------------- ### Define Legacy Classes with Constructor Arguments Source: https://structuremap.github.io/registration/policies Example classes that require a 'connectionString' constructor argument. These demonstrate a scenario where a policy can automate dependency injection for common arguments. ```csharp public class DatabaseUser { public string ConnectionString { get; set; } public DatabaseUser(string connectionString) { ConnectionString = connectionString; } } public class ConnectedThing { public string ConnectionString { get; set; } public ConnectedThing(string connectionString) { ConnectionString = connectionString; } } ``` -------------------------------- ### Install Strong-Named StructureMap via NuGet Source: https://structuremap.github.io/get-structuremap Use this command if you require a strong-named version of the StructureMap assembly. ```powershell PM> Install-Package structuremap-signed ``` -------------------------------- ### Get Build Plan for a Named Instance Source: https://structuremap.github.io/diagnostics/build-plans Retrieve the build plan for a specific named instance of a plugin type. Use this when you have multiple configurations for the same type. ```csharp var description = theContainer.Model.For() .Find("A") .DescribeBuildPlan(); ``` -------------------------------- ### Get Instance by PluginType Source: https://structuremap.github.io/resolving/get-a-service-by-plugintype Demonstrates how to retrieve the default configured object of a plugin type using the IContainer.GetInstance() method. This can be done using either the generic type or the typeof operator. ```APIDOC ## Get Instance by PluginType ### Description Requesting the default configured object of a plugin type is done through the `IContainer.GetInstance()` method. ### Method `IContainer.GetInstance()` or `IContainer.GetInstance(Type type)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp [Fact] public void get_the_default_instance() { var container = new Container(x => { x.For().Use(); }); // Using generic type container.GetInstance() .ShouldBeOfType(); // Using typeof operator container.GetInstance(typeof(IWidget)) .ShouldBeOfType(); } ``` ### Response #### Success Response (200) An instance of the requested plugin type. #### Response Example (Implicitly demonstrated in the Request Example where the returned object is asserted to be of type AWidget) ``` -------------------------------- ### StructureMap Exception for Missing Default Instance (Pre-3.0) Source: https://structuremap.github.io/glossary This is an example of a StructureMap exception message from versions prior to 3.0, indicating that no default instance was defined for a given plugin type. ```text StructureMap Exception Code: 202 No Default Instance defined for PluginFamily [plugin type] ``` -------------------------------- ### Try Get Instance by Name and Generic Type Source: https://structuremap.github.io/resolving/try-geting-an-optional-service-by-plugin-type-and-name Use `TryGetInstance(name)` to retrieve an instance by its generic type and name. This method returns an instance if found, otherwise null. Ensure the service is registered before attempting to retrieve it. ```csharp [Fact] public void TryGetInstanceViaNameAndGeneric_ReturnsInstance_WhenTypeFound() { addColorInstance("Red"); addColorInstance("Orange"); addColorInstance("Blue"); // "Orange" exists, so an object should be returned var instance = _container.TryGetInstance("Orange"); instance.ShouldBeOfType(typeof(ColorRule)); } ``` -------------------------------- ### Demonstrating Auto-Wiring with Build Plan Source: https://structuremap.github.io/the-container/auto-wiring This snippet shows how to configure a StructureMap container and then inspect the build plan for a class, demonstrating how auto-wiring resolves dependencies through its public constructor. ```csharp public void ShowBuildPlan() { var container = new Container(_ => { _.For().Use(); _.For().Use(); }); // Just proving that we can build ShippingScreenPresenter;) container.GetInstance().ShouldNotBeNull(); var buildPlan = container.Model.For().Default.DescribeBuildPlan(1); Debug.WriteLine(buildPlan); } ``` -------------------------------- ### Configure StructureMap Container with Registry Source: https://structuremap.github.io/registration Demonstrates three methods for initializing a StructureMap container using a Registry class: passing an instance, adding the registry via configuration, or using a static factory method. ```csharp // Example #1 var container1 = new Container(new FooBarRegistry()); // Example #2 var container2 = new Container(c => { c.AddRegistry(); }); // Example #3 -- create a container for a single Registry var container3 = Container.For(); ``` -------------------------------- ### Supply Named Constructor Arguments Source: https://structuremap.github.io/resolving/passing-arguments-at-runtime Demonstrates how to supply primitive arguments to constructors at runtime. The first part shows initial configuration, and the second part uses `container.With()` to override the 'color' argument for `IWidget`. ```csharp [Fact] public void supply_named_arguments() { var container = new Container(x => { x.For().Use().Ctor().Is("Red"); }); container.GetInstance() .ShouldBeOfType() .Color.ShouldBe("Red"); container.With("color").EqualTo("Blue") .GetInstance() .ShouldBeOfType() .Color.ShouldBe("Blue"); } ``` -------------------------------- ### Get Default Instance of a Service Source: https://structuremap.github.io/resolving/get-a-service-by-plugintype Use IContainer.GetInstance() for generic type retrieval or IContainer.GetInstance(Type) for non-generic retrieval to get the default configured object for a plugin type. ```csharp [Fact] public void get_the_default_instance() { var container = new Container(x => { x.For().Use(); }); container.GetInstance() .ShouldBeOfType(); // or container.GetInstance(typeof(IWidget)) .ShouldBeOfType(); } ``` -------------------------------- ### Define Services for StructureMap Source: https://structuremap.github.io/registration Defines interfaces and concrete classes used in StructureMap configuration examples. ```csharp public interface IBar { } public class Bar : IBar { } public interface IFoo { } public class Foo : IFoo { public IBar Bar { get; private set; } public Foo(IBar bar) { Bar = bar; } } ``` -------------------------------- ### Registering and Using a Custom Constructor Selector Source: https://structuremap.github.io/registration/constructor-selection Demonstrates how to register a custom constructor selector policy and verifies its behavior by resolving instances of Thing1 and Thing2. ```csharp [Fact] public void use_a_custom_constructor_selector() { var container = new Container (_ => { _.For().Use(); _.Policies.ConstructorSelector(); }); container.GetInstance() .CorrectCtorWasUsed.ShouldBeTrue(); container.GetInstance() .CorrectCtorWasUsed.ShouldBeTrue(); } ``` -------------------------------- ### StructureMap Decorator Registration Example Source: https://structuremap.github.io/interception-and-decorators Configures StructureMap to decorate all IWidget registrations with WidgetHolder and sets AWidget as the default implementation. ```csharp [Fact] public void decorator_example() { var container = new Container(_ => { // This usage adds the WidgetHolder as a decorator // on all IWidget registrations and makes AWidget // the default _.For().DecorateAllWith(); _.For().Use(); }); container.GetInstance() .ShouldBeOfType() .Inner.ShouldBeOfType(); } ``` -------------------------------- ### Configure Lifecycles and Test Precedence Source: https://structuremap.github.io/object-lifecycle/configuring-lifecycles Demonstrates configuring default lifecycles for plugin types and specific instances, then verifies the precedence rules. ```csharp [Fact] public void lifecycle_precedence() { var container = new Container(x => { x.For().Use(); // Configure the default lifecycle for // a PluginType (Rule) x.For().Singleton(); x.For().Add().Named("C"); // Configure the lifecycle for a single Instance x.For().Add().Named("A").Transient(); x.For().Add().Named("B").AlwaysUnique(); }); // The default lifecycle is Transient container.Model.For().Default .Lifecycle.ShouldBeOfType(); // Override at the Family container.Model.For().Lifecycle.ShouldBeOfType(); container.Model.For().Find("C").Lifecycle.ShouldBeOfType(); // 'C' is the default lifecycle for Rule (SingletonThing) container.GetInstance("C") .ShouldBeTheSameAs(container.GetInstance("C")); // 'A' is a transient container.GetInstance("A") .ShouldNotBeTheSameAs(container.GetInstance("A")); using (var nested = container.GetNestedContainer()) { // 'B' is always unique nested.GetInstance("B") .ShouldNotBeTheSameAs(nested.GetInstance("B")); } } ``` -------------------------------- ### Generate Basic Container Report Source: https://structuremap.github.io/diagnostics/whatdoihave Use this to get a general textual report of the current configuration of a running StructureMap container. ```csharp var container = new Container(); var report = container.WhatDoIHave(); Debug.WriteLine(report); ``` -------------------------------- ### Define Default Services with UseIfNone() Source: https://structuremap.github.io/registration/fallback-services Use `UseIfNone()` to register a default implementation for a service. This implementation will only be used if no other concrete registration for the service is found. ```csharp public class DefaultServices : Registry { public DefaultServices() { // If nobody else provides a default // for IWidget, use AWidget For().UseIfNone(); } } ``` ```csharp public class SpecificServices : Registry { public SpecificServices() { // Use BWidget for IWidget, period For().Use(); } } ``` -------------------------------- ### Define Rule Interface and Implementation Source: https://structuremap.github.io/the-container/handling-missing-named-instances Defines a simple 'Rule' interface and a 'ColorRule' implementation used in examples for missing named instances. ```csharp public interface Rule { } public class ColorRule : Rule { public string Color { get; set; } public ColorRule(string color) { Color = color; } } ``` -------------------------------- ### Demonstrate Child Container in Action Source: https://structuremap.github.io/the-container/profiles-and-child-containers Shows how to create a child container that overrides specific registrations while falling back to the parent for others. Useful for isolating configuration changes for specific parts of an application. ```csharp [ Fact ] public void show_a_child_container_in_action() { var parent = new Container(_ => { _.For().Use(); _.For().Use(); }); // Create a child container and override the // IService registration var child = parent.CreateChildContainer(); child.Configure(_ => { _.For().Use(); }); // The child container has a specific registration // for IService, so use that one child.GetInstance() .ShouldBeOfType(); // The child container does not have any // override of IWidget, so it uses its parent's // configuration to resolve IWidget child.GetInstance() .ShouldBeOfType(); } ``` -------------------------------- ### Custom AllInterfacesConvention Implementation Source: https://structuremap.github.io/registration/auto-registration-and-conventions An example implementation of `IRegistrationConvention` that registers a concrete type against all interfaces it implements. It filters for concrete, closed types. ```csharp public interface IFoo { } public interface IBar { } public interface IBaz { } public class BusyGuy : IFoo, IBar, IBaz { } // Custom IRegistrationConvention public class AllInterfacesConvention : IRegistrationConvention { public void ScanTypes(TypeSet types, Registry registry) { // Only work on concrete types types.FindTypes(TypeClassification.Concretes | TypeClassification.Closed).Each(type => { // Register against all the interfaces implemented // by this concrete class type.GetInterfaces().Each(@interface => registry.For(@interface).Use(type)); }); } } ``` -------------------------------- ### Configure a Profile with Default Instance Source: https://structuremap.github.io/the-container/profiles-and-child-containers Demonstrates how to define a named profile with specific service registrations. Profiles are useful for establishing different service resolutions for different application modes or user types. ```csharp [ Fact ] public void Add_default_instance_with_concrete_type() { IContainer container = new Container(registry => { registry.Profile("something", p => { p.For().Use(); p.For().Use(); }); }); var profile = container.GetProfile("something"); profile.GetInstance().ShouldBeOfType(); profile.GetInstance().ShouldBeOfType(); } ``` -------------------------------- ### Custom Interception Policy Example Source: https://structuremap.github.io/interception-and-decorators This custom policy decorates all IWidget instances with WidgetHolder. Ensure DecoratorInterceptor is available and configured correctly. ```csharp public class CustomInterception : IInterceptorPolicy { public string Description { get { return "good interception policy"; } } public IEnumerable DetermineInterceptors(Type pluginType, Instance instance) { if (pluginType == typeof(IWidget)) { yield return new DecoratorInterceptor(typeof(IWidget), typeof(WidgetHolder)); } } } ``` -------------------------------- ### LoggerConvention for Construction Policies Source: https://structuremap.github.io/the-container/working-with-the-icontext-at-build-time An example of a custom Construction Policy that injects a Logger based on the type being constructed. This is an alternative to using IContext directly at runtime. ```csharp public class LoggerConvention : ConfiguredInstancePolicy { protected override void apply(Type pluginType, IConfiguredInstance instance) { instance.Constructor .GetParameters() .Where(param => param.ParameterType == typeof(Logger)) .Each(param => instance.Dependencies.Add(LoggerFactory.LoggerFor(instance.PluggedType))); } } ``` -------------------------------- ### Registering Services with Constructor Arguments Source: https://structuremap.github.io/registration Configure a container to register a service and provide a primitive constructor argument. This is useful for types like SqlConnection that require configuration values. ```csharp var container = new Container(c => { //just for demo purposes, normally you don't want to embed the connection string directly into code. c.For().Use().Ctor().Is("YOUR_CONNECTION_STRING"); //a better way would be providing a delegate that retrieves the value from your app config. }); ``` -------------------------------- ### Inline Constructor Arguments Registration Source: https://structuremap.github.io/registration/inline-dependencies Demonstrates various methods for registering inline constructor arguments for SimpleRule dependencies. ```csharp public class InlineCtorArgs : Registry { public InlineCtorArgs() { // Defining args by type For().Use() .Ctor().Is() .Ctor().Is() .Named("One"); // Pass the explicit values for dependencies For().Use() .Ctor().Is(new Condition2()) .Ctor().Is(new Action2()) .Named("Two"); // Use Lambda construction For().Use() .Ctor().Is(() => new Condition3()) .Ctor().Is("some crazy builder", c => c.GetInstance()) .Named("Three"); // Rarely used, but gives you a "do any crazy thing" option // Pass in your own Instance object For().Use() .Ctor().Is(new MySpecialActionInstance()); // Inline configuration of your dependency's dependencies For().Use() .Ctor().IsSpecial(_ => _.Type().Ctor().Is(100)) // or .Ctor().Is(new SmartInstance().Ctor().Is(100)); } public class BigCondition : ICondition { public BigCondition(int number) { } public bool Matches(SomeEvent @event) { throw new NotImplementedException(); } } public class MySpecialActionInstance : LambdaInstance { public MySpecialActionInstance() : base(() => new Action3()) { } } } ``` -------------------------------- ### Reflecting over Constructor Parameters Source: https://structuremap.github.io/registration/configured-instance Shows how to inspect the constructor parameters of an IConfiguredInstance using .Net Reflection. ```csharp public class GuyWithArguments { public GuyWithArguments(IWidget widget, Rule rule) { } } [Fact] public void reflecting_over_constructor_args() { IConfiguredInstance instance = new SmartInstance() // I'm just forcing it to assign the constructor function .SelectConstructor(() => new GuyWithArguments(null, null)); instance.Constructor.GetParameters().Select(x => x.Name) .ShouldHaveTheSameElementsAs("widget", "rule"); } ``` -------------------------------- ### Nested Containers from Profiles Source: https://structuremap.github.io/the-container/nested-containers Illustrates creating nested containers from profile configurations. This allows for distinct configurations to be applied to nested scopes. ```csharp [Fact] public void nested_container_from_profile_container() { var container = new Container(x => { x.For().Use(); x.Profile("Blue", _ => _.For().Use()); x.Profile("Green", _ => _.For().Use()); }); using (var nested = container.GetProfile("Blue").GetNestedContainer()) { nested.GetInstance().ShouldBeOfType(); } using (var nested = container.GetNestedContainer("Green")) { nested.GetInstance().ShouldBeOfType(); } } ``` -------------------------------- ### Define Services Consuming IDatabase Source: https://structuremap.github.io/registration/policies Defines example service classes (BigService, ImportantService, DoubleDatabaseUser) that depend on IDatabase, specifying which named database they require via constructor parameters. ```csharp public class BigService { public BigService(IDatabase green) { DB = green; } public IDatabase DB { get; set; } } public class ImportantService { public ImportantService(IDatabase red) { DB = red; } public IDatabase DB { get; set; } } public class DoubleDatabaseUser { public DoubleDatabaseUser(IDatabase red, IDatabase green) { Red = red; Green = green; } // Watch out for potential conflicts between setters // and ctor params. The easiest thing is to just make // setters private public IDatabase Green { get; private set; } public IDatabase Red { get; private set; } } ``` -------------------------------- ### Func for Lazy Singleton Resolution Source: https://structuremap.github.io/the-container/lazy-resolution Inject `Func` to lazily resolve a dependency. This example demonstrates resolving a singleton widget, ensuring multiple calls to the function return the same instance. ```csharp [Fact] public void build_a_func_that_returns_a_singleton() { var container = new Container(x => { x.ForSingletonOf().Use().Ctor("color").Is("green"); }); var func = container.GetInstance>(); var w1 = func(); var w2 = func(); var w3 = func(); w1.ShouldBeOfType().Color.ShouldBe("green"); w1.ShouldBeTheSameAs(w2); w1.ShouldBeTheSameAs(w3); w2.ShouldBeTheSameAs(w3); } ``` -------------------------------- ### Implement DummyService Source: https://structuremap.github.io/autofactory Provides a concrete implementation of the IDummyService interface. ```csharp public class DummyService : IDummyService { public string Name { get; set; } } ``` -------------------------------- ### Registering Logger with IContext and ParentType Source: https://structuremap.github.io/the-container/working-with-the-icontext-at-build-time Demonstrates registering a Logger dependency using IContext.ParentType to inject a logger specific to the type being created. AlwaysUnique() ensures each instance gets its own logger. ```csharp [Fact] public void can_happily_use_the_parent_type() { var container = new Container(x => { // AlwaysUnique() is important so that every object created will get // their own Logger instead of sharing whichever one is created first x.For().Use(c => LoggerFactory.LoggerFor(c.ParentType)).AlwaysUnique(); }); var top = container.GetInstance(); top.Logger.ParentType.ShouldBe(typeof(LoggedClass1)); top.Child.Logger.ParentType.ShouldBe(typeof(LoggedClass2)); top.Child.Child.Logger.ParentType.ShouldBe(typeof(LoggedClass3)); } ``` -------------------------------- ### Use ILogVisualizer with StructureMap Source: https://structuremap.github.io/generics Demonstrates how to obtain an ILogVisualizer instance from a StructureMap container and use it to convert a specific log object to HTML. ```csharp // Just setting up a Container and ILogVisualizer var container = Container.For(); var visualizer = container.GetInstance(); // If I have an IssueCreated lob object... var created = new IssueCreated(); // I can get the html representation: var html = visualizer.ToHtml(created); ``` -------------------------------- ### Pass Arguments with Fluent Interface Source: https://structuremap.github.io/resolving/passing-arguments-at-runtime Uses the `IContainer.With()` fluent interface to pass specific instances of `IWidget` and `IService` when getting an instance of `GuyWithWidgetAndService`. This overrides the default registrations for these interfaces. ```csharp var widget = new BWidget(); var service = new BService(); var guyWithWidgetAndService = container .With(widget) .With(service) .GetInstance(); guyWithWidgetAndService .Widget.ShouldBeTheSameAs(widget); guyWithWidgetAndService .Service.ShouldBeTheSameAs(service); ``` -------------------------------- ### Include Default and Scan for Specific Registrations Source: https://structuremap.github.io/registration/fallback-services Include default registries using `IncludeRegistry()` and scan for other registries in assemblies. Registrations found during the scan will take precedence over `UseIfNone()` registrations. ```csharp [AttributeUsage(AttributeTargets.Assembly)] public class ProductModuleAttribute : Attribute { } public class ApplicationRegistry : Registry { public ApplicationRegistry() { // Use the default services as fallbacks IncludeRegistry(); // Dependending on what assemblies are present, // this might find specific registrations that // will take precedence over the UseIfNone() // registrations in DefaultServices Scan(_ => { _.AssembliesFromApplicationBaseDirectory( assem => assem.HasAttribute()); _.LookForRegistries(); }); } } ``` -------------------------------- ### Exercise Named Database Injection Policy Source: https://structuremap.github.io/registration/policies Demonstrates retrieving instances of the services and verifies that the correct named IDatabase implementations ('red' or 'green') have been injected based on the constructor parameter names. ```csharp // ImportantService should get the "red" database container.GetInstance() .DB.As().ConnectionString.ShouldBe("*red*"); // BigService should get the "green" database container.GetInstance() .DB.As().ConnectionString.ShouldBe("*green*"); // DoubleDatabaseUser gets both var user = container.GetInstance(); user.Green.As().ConnectionString.ShouldBe("*green*"); user.Red.As().ConnectionString.ShouldBe("*red*"); ``` -------------------------------- ### Creating and Using a Nested Container Source: https://structuremap.github.io/the-container/nested-containers Demonstrates how to create a nested container from an existing IContainer and resolve services within its scope. Objects resolved from the nested container are disposed when the nested container is disposed. ```csharp public interface IWorker { void DoWork(); } public class Worker : IWorker, IDisposable { public void DoWork() { // do stuff! } public void Dispose() { // clean up } } [Fact] public void creating_a_nested_container() { // From an IContainer object var container = new Container(_ => { _.For().Use(); }); using (var nested = container.GetNestedContainer()) { // This object is disposed when the nested container // is disposed var worker = nested.GetInstance(); worker.DoWork(); } ``` -------------------------------- ### Inspect Type Scanning with WhatDidIScan Source: https://structuremap.github.io/diagnostics/type-scanning Call `Container.WhatDidIScan()` to get a textual report of all type scanning operations performed by the container. This helps in understanding which assemblies were scanned and which conventions were applied. ```csharp var container = new Container(_ => { _.Scan(x => { x.TheCallingAssembly(); x.WithDefaultConventions(); x.RegisterConcreteTypesAgainstTheFirstInterface(); x.SingleImplementationsOfInterface(); }); _.Scan(x => { // Give your scanning operation a descriptive name // to help the diagnostics to be more useful x.Description = "Second Scanner"; x.AssembliesFromApplicationBaseDirectory(assem => assem.FullName.Contains("Widget")); x.ConnectImplementationsToTypesClosing(typeof(IService<>)); x.AddAllTypesOf(); }); }); Debug.WriteLine(container.WhatDidIScan()); ``` ```text /* All Scanners ================================================================ Scanner #1 Assemblies ---------- * StructureMap.Testing, Version=4.0.0.51243, Culture=neutral, PublicKeyToken=null Conventions -------- * Default I[Name]/[Name] registration convention * Register all concrete types against the first interface (if any) that they implement * Register any single implementation of any interface against that interface Second Scanner Assemblies ---------- * StructureMap.Testing.GenericWidgets, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null * StructureMap.Testing.Widget, Version=4.0.0.51243, Culture=neutral, PublicKeyToken=null * StructureMap.Testing.Widget2, Version=4.0.0.51243, Culture=neutral, PublicKeyToken=null * StructureMap.Testing.Widget3, Version=4.0.0.51243, Culture=neutral, PublicKeyToken=null * StructureMap.Testing.Widget4, Version=4.0.0.51243, Culture=neutral, PublicKeyToken=null * StructureMap.Testing.Widget5, Version=4.0.0.51243, Culture=neutral, PublicKeyToken=null Conventions -------- * Connect all implementations of open generic type IService * Find and register all types implementing StructureMap.Testing.Widget.IWidget */ ``` -------------------------------- ### Configure StructureMap Container Directly Source: https://structuremap.github.io/registration Shows two ways to create and configure a StructureMap container: passing configuration directly to the constructor or configuring it after creation. ```csharp // Example #1 - Create an container instance and directly pass in the configuration. var container1 = new Container(c => { c.For().Use(); c.For().Use(); }); // Example #2 - Create an container instance but add configuration later. var container2 = new Container(); container2.Configure(c => { c.For().Use(); c.For().Use(); }); ``` -------------------------------- ### Implement Custom FuncInstance with LambdaInstance Source: https://structuremap.github.io/instances Subclass LambdaInstance to create a custom Instance type for Func. This example shows how to pass a Func to the base constructor and override the Description property. ```csharp public class FuncInstance : LambdaInstance> { // Pass a Func into the base constructor // Use a static method for cleaner syntax to avoid the // nasty Lambda syntax formatting as needed public FuncInstance() : base(s => s.GetInstance().GetInstance) { } public override string Description { get { return "Constructor for Func<{0}>".ToFormat(typeof (T).Name); } } } ``` -------------------------------- ### Register and Verify Singleton Cache Source: https://structuremap.github.io/registration/policies Demonstrates registering a WidgetCache implementation with the CacheIsSingleton policy and verifies that it is indeed a singleton. The policy is applied when StructureMap creates a build plan. ```csharp [Fact] public void set_cache_to_singleton() { var container = new Container(_ => { _.Policies.Add(); _.For().Use(); }); // The policy is applied *only* at the time // that StructureMap creates a "build plan" container.GetInstance() .ShouldBeTheSameAs(container.GetInstance()); // Now that the policy has executed, we // can verify that WidgetCache is a SingletonThing container.Model.For().Default .Lifecycle.ShouldBeOfType(); } ``` -------------------------------- ### ISettingsProvider Interface and Implementation Source: https://structuremap.github.io/registration/on-missing-family-policies Defines and implements an interface for retrieving settings, with a basic AppSettingsProvider. ```csharp public interface ISettingsProvider { T SettingsFor() where T : class, new(); object SettingsFor(Type settingsType); } public class AppSettingsProvider : ISettingsProvider { public T SettingsFor() where T : class, new() { return SettingsFor(typeof (T)).As(); } public object SettingsFor(Type settingsType) { // The real one reads key/value data from // the appSettings and uses FubuCore's // model binding to assign data to a new // object of settingsType return null; } } ``` -------------------------------- ### Configure and Resolve with Explicit Registration Source: https://structuremap.github.io/quickstart Demonstrates explicitly configuring a StructureMap Container and resolving an object instance. ```csharp // Configure and build a brand new // StructureMap Container object var container = new Container(_ => { _.For().Use(); _.For().Use(); }); // Now, resolve a new object instance of IFoo container.GetInstance() // should be type Foo .ShouldBeOfType() // and the IBar dependency too .Bar.ShouldBeOfType(); ``` -------------------------------- ### Get Named Service Instance Source: https://structuremap.github.io/resolving/get-a-service-by-plugin-type-and-name Demonstrates retrieving named instances of IWidget using both generic and typeof overloads of GetInstance. Ensure the service is registered with a name using .Named() during container configuration. ```csharp [Fact] public void get_a_named_instance() { var container = new Container(x => { x.For().Add().Named("A"); x.For().Add().Named("B"); x.For().Add().Named("C"); }); container.GetInstance("A").ShouldBeOfType(); container.GetInstance("B").ShouldBeOfType(); container.GetInstance("C").ShouldBeOfType(); // or container.GetInstance(typeof(IWidget), "A").ShouldBeOfType(); container.GetInstance(typeof(IWidget), "B").ShouldBeOfType(); container.GetInstance(typeof(IWidget), "C").ShouldBeOfType(); } ``` -------------------------------- ### AlwaysUnique Lifecycle Example Source: https://structuremap.github.io/object-lifecycle/supported-lifecycles Demonstrates that AlwaysUnique creates a new object instance on every request, even within nested containers or within a single request's object graph. Instances are not tracked or disposed by StructureMap. ```csharp [Fact] public void Always_Unique() { var c = new Container(x => { x.For().Use().AlwaysUnique(); }); // In a normal container, you get a new object // instance of the Service class in subsequent // requests c.GetInstance() .ShouldNotBeTheSameAs(c.GetInstance()) .ShouldNotBeTheSameAs(c.GetInstance()); // Within a nested container, 'Transient' now // means within the Nested Container. // A nested container is effectively one request using (var nested = c.GetNestedContainer()) { nested.GetInstance() .ShouldNotBeTheSameAs(nested.GetInstance()) .ShouldNotBeTheSameAs(nested.GetInstance()); } // Even in a single request, var holder = c.GetInstance(); holder.Service.ShouldNotBeTheSameAs(holder.User.Service); } ``` -------------------------------- ### Manipulate Individual Instances Source: https://structuremap.github.io/diagnostics/using-the-container-model Find the model for a single instance, build or resolve an object, test if a singleton has been created, eject a singleton, test the lifecycle, describe the build plan, and access the raw instance model. ```csharp // First, find the model for a single Instance var instance = container.Model.For().Default; // build or resolve an object for this Instance cast to // the type specified to the Get() method instance.Get().ShouldBeOfType(); // if the instance is configured as a SingletonThing, test // if the SingletonThing object has already been created var hasSingletonBeenCreated = instance.ObjectHasBeenCreated(); if (hasSingletonBeenCreated) { // remove the SingletonThing object from the cache so that // StructureMap will be forced to rebuild this object instance.EjectObject(); } // test the lifecycle of this instance instance.Lifecycle.ShouldBeOfType(); // Visualize the build plan no more than 3 levels deep Debug.WriteLine(instance.DescribeBuildPlan(3)); // Get at the underlying Instance model that StructureMap itself // uses. Be cautious using this. var rawModel = instance.Instance; ``` -------------------------------- ### Retrieve All Instances of a Plugin Type Source: https://structuremap.github.io/resolving/get-all-services-by-plugin-type Use GetAllInstances() to get all configured instances of a generic type. Alternatively, use GetAllInstances(typeof(T)) for non-generic retrieval, ensuring to cast the results if necessary. The order of instances returned matches the order they were configured. ```csharp using StructureMap; using Xunit; using Shouldly; public class Widget {} public class AWidget : Widget {} public class BWidget : Widget {} public class CWidget : Widget {} public class get_all_instances { [Fact] public void get_all_instances() { var container = new Container(x => { x.For().Add().Named("A"); x.For().Add().Named("B"); x.For().Add().Named("C"); }); container.GetAllInstances() .Select(x => x.GetType()) .ShouldHaveTheSameElementsAs(typeof(AWidget), typeof(BWidget), typeof(CWidget)); // or container.GetAllInstances(typeof(IWidget)) .OfType() // returns an IEnumerable, so I'm casting here .Select(x => x.GetType()) .ShouldHaveTheSameElementsAs(typeof(AWidget), typeof(BWidget), typeof(CWidget)); } } ``` -------------------------------- ### Implement MathService Source: https://structuremap.github.io/dynamic-interception Provides a concrete implementation of the IMathService interface. ```csharp private class MathService : IMathService { public int GetSquareRoot(int value) { return (int)Math.Sqrt(value); } public async Task GetSquareRootAsync(int value) { await Task.Yield(); return (int)Math.Sqrt(value); } } ``` -------------------------------- ### Test UseIfNone() Behavior Source: https://structuremap.github.io/registration/fallback-services Verify that `UseIfNone()` correctly falls back to the default implementation when no other registrations exist, and that specific registrations override the fallback. ```csharp [Fact] public void see_use_if_none_in_action() { var container1 = Container.For(); // No other registrations, so fallback // to AWidget container1.GetInstance() .ShouldBeOfType(); var container2 = new Container(_ => { // add both registries above // NOTE: the order does not matter for IWidget _.IncludeRegistry(); _.IncludeRegistry(); }); // The registration in SpecificServices // should win out container2.GetInstance() .ShouldBeOfType(); } ``` -------------------------------- ### Visualize Registry with Type Scanning and Fallback Source: https://structuremap.github.io/generics Demonstrates the VisualizationRegistry combining type scanning with default fallback behavior for log types. This is useful when you have specific visualizers for certain types but want a default for others. ```csharp [Fact] public void visualization_registry() { var container = Container.For(); Debug.WriteLine(container.WhatDoIHave(@namespace: "StructureMap.Testing.Acceptance.Visualization")); container.GetInstance>() .ShouldBeOfType(); container.GetInstance>() .ShouldBeOfType(); // We have no special registration for TaskAssigned, // so fallback to the default visualizer container.GetInstance>() .ShouldBeOfType>(); } ``` -------------------------------- ### Changing Instance Lifecycle Source: https://structuremap.github.io/registration/configured-instance Demonstrates how to override the lifecycle of a single IConfiguredInstance using various methods. ```csharp IConfiguredInstance instance = new ConfiguredInstance(typeof(WidgetHolder)); // Use the SingletonThing lifecycle instance.Singleton(); // or supply an ILifecycle type instance.SetLifecycleTo(); // or supply an ILifecycle object instance.SetLifecycleTo(new Lifecycles_Samples.MyCustomLifecycle()); // or override to the default "transient" lifecycle instance.DefaultLifecycle(); ``` -------------------------------- ### Implement IAutoFactoryConventionProvider Source: https://structuremap.github.io/autofactory Interface for providing custom Auto-factory conventions. ```csharp public interface IAutoFactoryConventionProvider { IAutoFactoryMethodDefinition GetMethodDefinition(MethodInfo methodInfo, IList arguments); } ``` -------------------------------- ### Traditional Singleton Implementation Source: https://structuremap.github.io/object-lifecycle Illustrates the classic Singleton pattern, which can lead to negative effects on code maintainability and testability. ```csharp public class EvilSingleton { public static readonly EvilSingleton Instance = new EvilSingleton(); private EvilSingleton() { } public void DoSomething() { // do something with the static data here } } public class EvilSingletonUser { public void DoWork() { EvilSingleton.Instance.DoSomething(); } } ``` -------------------------------- ### Equivalent Registration with Lambda Expressions Source: https://structuremap.github.io/the-container/forwarding-requests-for-a-type-to-another-type Achieve the same result as `Forward()` using lambda registrations. This approach explicitly uses `Use(c => c.GetInstance())` for each interface, ensuring they resolve to the same singleton instance. ```csharp [Fact] public void equivalent() { var container = new Container(_ => { // Let's make StatefulCache a SingletonThing in the container _.ForConcreteType().Configure.Singleton(); _.For().Use(c => c.GetInstance()); _.For().Use(c => c.GetInstance()); }); container.GetInstance().ShouldBeOfType(); container.GetInstance().ShouldBeOfType(); } ``` -------------------------------- ### FuncInterceptor Constructor with Expression> Source: https://structuremap.github.io/interception-and-decorators Creates a FuncInterceptor using a user-supplied expression that takes the object to be decorated and returns the decorated object. An optional description can be provided. ```csharp public FuncInterceptor(Expression> expression, string description = null) ``` -------------------------------- ### Build Plan for AppSettingTarget Source: https://structuremap.github.io/registration/attributes Displays the StructureMap build plan for `AppSettingTarget`, illustrating how the custom attribute influences dependency injection for constructor parameters and setter properties. ```text PluginType: StructureMap.Testing.Acceptance.attribute_usage+AppSettingTarget Lifecycle: Transient new AppSettingTarget(String name) ┗ String name = Value: Jeremy Set String HomeState = Value: Missouri ``` -------------------------------- ### Applying SingletonAttribute to Interfaces and Classes Source: https://structuremap.github.io/registration/attributes Demonstrates how to apply the `SingletonAttribute` to an interface to make all its implementations singletons by default, and to a concrete class to make that specific type a singleton. ```csharp [Singleton] // ALL Instance's of ITeamCache will be singletons by default public interface ITeamCache { } public class TeamCache : ITeamCache { } public class OtherTeamCache : ITeamCache { } public interface ITeam { } public class Chargers : ITeam { } [Singleton] // This specific type will be a singleton public class Chiefs : ITeam { } ```