Last active
March 14, 2020 15:27
-
-
Save jongleur1983/5d45dd6034fc554c5f2d0a054444924d to your computer and use it in GitHub Desktop.
Autofac question
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 System.Collections.Generic; | |
using System.Reflection; | |
using System.Text; | |
using System.Xml; | |
using Autofac; | |
namespace AutofacTest | |
{ | |
/// <summary> | |
/// Attribute that marks parameters that must be given by hand. | |
/// </summary> | |
public class ParameterAttribute : Attribute { } | |
/// <summary> | |
/// just an item that should never be resolved | |
/// </summary> | |
public struct DataItem | |
{ | |
public string Content { get; set; } | |
} | |
public interface IImportXml | |
{ | |
IEnumerable<DataItem> ImportData(); | |
} | |
public class ImportXml : IImportXml | |
{ | |
public ImportXml( | |
Func<string, XmlReader> readerForFile, // to be resolved | |
[Parameter] XmlSettings settings) // to be defined manually | |
{ | |
} | |
public IEnumerable<DataItem> ImportData() | |
{ | |
yield break; | |
} | |
} | |
public interface IImportData{} | |
public class SettingsAgnosticImportXml : IImportData | |
{ | |
public SettingsAgnosticImportXml( | |
Func<string, XmlReader> readerForFile, // to be resolved | |
XmlSettings settings) // to be resolved, too! | |
{ | |
} | |
} | |
public class XmlSettings | |
{ | |
public Encoding RequiredEncoding { get; set; } | |
} | |
public interface IDecodeXml | |
{ | |
IEnumerable<DataItem> ReadFile(XmlSettings settings); | |
} | |
public class AutofacTest | |
{ | |
private readonly IImportXml import; | |
public AutofacTest(IImportXml import) | |
{ | |
this.import = import; | |
} | |
public void DecodeXml(string filename) | |
{ | |
this.import.ImportData(); | |
} | |
public static void Main(string[] args) | |
{ | |
var builder = new ContainerBuilder(); | |
builder.Register<Func<string, XmlReader>>(context => s => XmlReader.Create(s)) | |
.SingleInstance(); | |
builder | |
.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(AutofacTest))) | |
.AsImplementedInterfaces() | |
.AsSelf(); | |
var container = builder.Build(); | |
// should be possible: | |
var getInstance = container.Resolve<Func<XmlSettings, AutofacTest>>(); | |
getInstance(new XmlSettings()) | |
.DecodeXml("testfile.xml"); | |
// should not be possible, as XmlSettings get auto-resolved here: | |
var instance = container.Resolve<AutofacTest>(); | |
// should be possible (although there's an XmlSettings parameter involved): | |
var agnostic = container.Resolve<IImportData>(); | |
instance.DecodeXml("testfile.xml"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment