Let me explain the scenario: when I hardcode the Domainname\Usergroup, the permission levels are working perfectly.
But what I want to do is instead of hardcoding the Domain\Usergroup in the code, I want to get it from the config file:
string xyz = ConfigurationManager.Appsettings["DomainKeyfromConfig"]
[PrincipalPermission(SecurityAction.Demand,Role = #xyz)]
public Response<String> GetString(String request)
{
// some code
}
When I'm trying to do this, I get this error
CS0182:An attribute argument must be a constant expression, typeof
expression or array creation expression of an attribute parameter type
Your screenshot has shown the specific reason for the error.You can't do that with attributes, they have to be constants as stated in the error message. If you wanted to get a value from the configuration file, you could do it by passing the key to the attribute, and then in the constructor get the value you want from the configurationmanager.https://stackoverflow.com/questions/31481820/an-attribute-argument-must-be-a-constant-expression-typeof-expression-or-array
public MyAttribute :Attribute
{
private string _config;
public MyAttribute(string configKey)
{
_config = ConfigurationManager.AppSettings[configKey];
...
}
}
I have a code that loads an assembly and categorize data by attributes.
I'm trying to get the actual CustomAttribute object.
During debug on net framework, the code returns a value.
Running the code on .Net5 returns null
Edit
After some digging in documentation:
.NET Framework version 2.0 provides a new load context, the reflection-only context, which can be used to examine code that cannot be loaded for execution.
https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/accessing-custom-attributes
Edit #2
The reason is that i'm trying to get the object during runtime, and as written in the documentaion quote above, the attribute as well as any other runtime reflection-only context is cannot be loaded, and the method returns null.
Is there any other solution other than using system.reflection to get the an actual attribute object on runtime?
The dictionary initialization
var ass = Assembly.LoadFile(Path.GetFullPath("MyInterface.dll"));
var asss = Assembly.GetExecutingAssembly();
var apiInterfaces = ass.DefinedTypes.Where(x => x.IsInterface && x.CustomAttributes != null && x.CustomAttributes.Any(z => z.AttributeType.FullName != null && z.AttributeType.FullName.Equals(typeof(ApiInterfaceDescriptorAttribute).FullName)));
The Attribute:
[AttributeUsage(AttributeTargets.Interface)]
public class ApiInterfaceDescriptorAttribute : Attribute
{
public string ApiUsageName { get; }
public ApiInterfaceDescriptorAttribute(string apiUsageName)
{
ApiUsageName = apiUsageName;
}
}
Sample interface
[ApiInterfaceDescriptor("powercontrol")]
public interface IMyInterface
{
[ApiMethodDescriptor(ApiExposureLevel.Basic, "a-method...")]
void SomeMethod();
}
The trial to get the attribute
public class ApiDetector
{
private Dictionary<Type, List<MethodInfo>> _apiDictionary = new Dictionary<Type, List<MethodInfo>>();
public void LoadApiElements()
{
var apiKeyDesriptor = key.GetCustomAttribute(typeof(ApiInterfaceDescriptorAttribute)) as ApiInterfaceDescriptorAttribute;
_apiDetector.Add(new ApiDataObjectDescriptor { Name = key.Name, ApiUsageName = apiKeyDesriptor?.ApiUsageName, Type = key });
}
}
when i ran this code locally i get the instance:
Running the code on .Net5 remote machine returns null:
Any help will be welcome.
Thanks ahead!
The root cause is the call to Assembly.LoadFile. This method always loads the specified assembly into its own AssemblyLoadContext. (More about assembly load context).
This means that you have the assembly loaded into the LoadFile load context (one copy) and I have a direct reference to it from your main code, which will load it into the default load context (second copy). While the assembly file is exactly the same, for the runtime these two copies are distinct assemblies and all types from the two will be treated as different types.
changing the assembly load method to:
Assembly.GetAssembly(typeof(MyType));
have resolved the problem.
thanks to vitek-karas from Microsoft support team.
Background: Noda Time contains many
serializable structs. While I dislike binary serialization, we
received many requests to support it, back in the 1.x timeline.
We support it by implementing the ISerializable interface.
We've received a recent issue
report of Noda
Time 2.x failing within .NET
Fiddle. The same code using Noda
Time 1.x works fine. The exception thrown is this:
Inheritance security rules violated while overriding member:
'NodaTime.Duration.System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo,
System.Runtime.Serialization.StreamingContext)'. Security
accessibility of the overriding method must match the security
accessibility of the method being overriden.
I've narrowed this down to the framework that's targeted: 1.x
targets .NET 3.5 (client profile); 2.x targets .NET 4.5. They have
big differences in terms of support PCL vs .NET Core and the
project file structure, but it looks like this is irrelevant.
I've managed to reproduce this in a local project, but I haven't
found a solution to it.
Steps to reproduce in VS2017:
Create a new solution
Create a new classic Windows console application targeting .NET
4.5.1. I called it "CodeRunner".
In the project properties, go to Signing and sign the assembly with
a new key. Untick the password requirement, and use any key file name.
Paste the following code to replace Program.cs. This is an
abbreviated version of the code in this Microsoft
sample.
I've kept all the paths the same, so if you want to go back to the
fuller code, you shouldn't need to change anything else.
Code:
using System;
using System.Security;
using System.Security.Permissions;
class Sandboxer : MarshalByRefObject
{
static void Main()
{
var adSetup = new AppDomainSetup();
adSetup.ApplicationBase = System.IO.Path.GetFullPath(#"..\..\..\UntrustedCode\bin\Debug");
var permSet = new PermissionSet(PermissionState.None);
permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
var fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence<System.Security.Policy.StrongName>();
var newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly);
var handle = Activator.CreateInstanceFrom(
newDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName,
typeof(Sandboxer).FullName
);
Sandboxer newDomainInstance = (Sandboxer) handle.Unwrap();
newDomainInstance.ExecuteUntrustedCode("UntrustedCode", "UntrustedCode.UntrustedClass", "IsFibonacci", new object[] { 45 });
}
public void ExecuteUntrustedCode(string assemblyName, string typeName, string entryPoint, Object[] parameters)
{
var target = System.Reflection.Assembly.Load(assemblyName).GetType(typeName).GetMethod(entryPoint);
target.Invoke(null, parameters);
}
}
Create another project called "UntrustedCode". This should be a
Classic Desktop Class Library project.
Sign the assembly; you can use a new key or the same one as for
CodeRunner. (This is partially to mimic the Noda Time situation,
and partly to keep Code Analysis happy.)
Paste the following code in Class1.cs (overwriting what's there):
Code:
using System;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
// [assembly: AllowPartiallyTrustedCallers]
namespace UntrustedCode
{
public class UntrustedClass
{
// Method named oddly (given the content) in order to allow MSDN
// sample to run unchanged.
public static bool IsFibonacci(int number)
{
Console.WriteLine(new CustomStruct());
return true;
}
}
[Serializable]
public struct CustomStruct : ISerializable
{
private CustomStruct(SerializationInfo info, StreamingContext context) { }
//[SecuritySafeCritical]
//[SecurityCritical]
//[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
}
}
Running the CodeRunner project gives the following exception (reformatted for readability):
Unhandled Exception: System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation.
--->
System.TypeLoadException:
Inheritance security rules violated while overriding member:
'UntrustedCode.CustomStruct.System.Runtime.Serialization.ISerializable.GetObjectData(...).
Security accessibility of the overriding method must match the security
accessibility of the method being overriden.
The commented-out attributes show things I've tried:
SecurityPermission is recommended by two different MS articles (first,
second), although
interestingly they do different things around explicit/implicit interface implementation
SecurityCritical is what Noda Time currently has, and is what this question's answer suggests
SecuritySafeCritical is somewhat suggested by Code Analysis rule messages
Without any attributes, Code Analysis rules are happy - with either SecurityPermission or SecurityCritical
present, the rules tell you to remove the attributes - unless you do have AllowPartiallyTrustedCallers. Following the suggestions in either case doesn't help.
Noda Time has AllowPartiallyTrustedCallers applied to it; the example here doesn't work either with or without the attribute applied.
The code runs without an exception if I add [assembly: SecurityRules(SecurityRuleSet.Level1)] to the UntrustedCode assembly (and uncomment the AllowPartiallyTrustedCallers attribute), but I believe that's a poor solution to the problem that could hamper other code.
I fully admit to being pretty lost when it comes to this sort of
security aspect of .NET. So what can I do to target .NET 4.5 and
yet allow my types to implement ISerializable and still be used in
environments such as .NET Fiddle?
(While I'm targeting .NET 4.5, I believe it's the .NET 4.0 security policy changes that caused the issue, hence the tag.)
According to the MSDN, in .NET 4.0 basically you should not use ISerializable for partially trusted code, and instead you should use ISafeSerializationData
Quoting from https://learn.microsoft.com/en-us/dotnet/standard/serialization/custom-serialization
Important
In versions previous to .NET Framework 4.0, serialization of custom user data in a partially trusted assembly was accomplished using the GetObjectData. Starting with version 4.0, that method is marked with the SecurityCriticalAttribute attribute which prevents execution in partially trusted assemblies. To work around this condition, implement the ISafeSerializationData interface.
So probably not what you wanted to hear if you need it, but I don't think there's any way around it while keeping using ISerializable (other than going back to Level1 security, which you said you don't want to).
PS: the ISafeSerializationData docs state that it is just for exceptions, but it doesn't seem all that specific, you may want to give it a shot... I basically can't test it with your sample code (other than removing ISerializable works, but you knew that already)... you'll have to see if ISafeSerializationData suits you enough.
PS2: the SecurityCritical attribute doesn't work because it's ignored when the assembly is loaded in partial trust mode (on Level2 security). You can see it on your sample code, if you debug the target variable in ExecuteUntrustedCode right before invoking it, it'll have IsSecurityTransparent to true and IsSecurityCritical to false even if you mark the method with the SecurityCritical attribute)
The accepted answer is so convincing that I almost believed this wasn't a bug. But after doing some experiments now I can say that Level2 security is a complete mess; at least, something is really fishy.
A couple of days ago I bumped into the same issue with my libraries. I quickly created a unit test; however, I could not reproduce the problem I experienced in .NET Fiddle, while the very same code "successfully" threw the exception in a console app. In the end I found two weird ways to overcome the issue.
TL;DR: It turns out that if you use an internal type of the used library in your consumer project, then the partially trusted code works as expected: it is able to instantiate an ISerializable implementation (and a security critical code cannot be called directly, but see below). Or, which is even more ridiculous, you can try to create the sandbox again if it didn't work for the first time...
But let's see some code.
ClassLibrary.dll:
Let's separate two cases: one for a regular class with security critical content and one ISerializable implementation:
public class CriticalClass
{
public void SafeCode() { }
[SecurityCritical]
public void CriticalCode() { }
[SecuritySafeCritical]
public void SafeEntryForCriticalCode() => CriticalCode();
}
[Serializable]
public class SerializableCriticalClass : CriticalClass, ISerializable
{
public SerializableCriticalClass() { }
private SerializableCriticalClass(SerializationInfo info, StreamingContext context) { }
[SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context) { }
}
One way to overcome the issue is to use an internal type from the consumer assembly. Any type will do it; now I define an attribute:
[AttributeUsage(AttributeTargets.All)]
internal class InternalTypeReferenceAttribute : Attribute
{
public InternalTypeReferenceAttribute() { }
}
And the relevant attributes applied to the assembly:
[assembly: InternalsVisibleTo("UnitTest, PublicKey=<your public key>")]
[assembly: AllowPartiallyTrustedCallers]
[assembly: SecurityRules(SecurityRuleSet.Level2, SkipVerificationInFullTrust = true)]
Sign the assembly, apply the key to the InternalsVisibleTo attribute and prepare for test project:
UnitTest.dll (uses NUnit and ClassLibrary):
To use the internal trick the test assembly should be signed as well. Assembly attributes:
// Just to make the tests security transparent by default. This helps to test the full trust behavior.
[assembly: AllowPartiallyTrustedCallers]
// !!! Comment this line out and the partial trust test cases may fail for the fist time !!!
[assembly: InternalTypeReference]
Note: The attribute can be applied anywhere. In my case it was on a method in a random test class took me a couple of days to find.
Note 2: If you run all test methods together it can happen that the tests will pass.
The skeleton of the test class:
[TestFixture]
public class SecurityCriticalAccessTest
{
private partial class Sandbox : MarshalByRefObject
{
}
private static AppDomain CreateSandboxDomain(params IPermission[] permissions)
{
var evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
var permissionSet = GetPermissionSet(permissions);
var setup = new AppDomainSetup
{
ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
};
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var strongNames = new List<StrongName>();
foreach (Assembly asm in assemblies)
{
AssemblyName asmName = asm.GetName();
strongNames.Add(new StrongName(new StrongNamePublicKeyBlob(asmName.GetPublicKey()), asmName.Name, asmName.Version));
}
return AppDomain.CreateDomain("SandboxDomain", evidence, setup, permissionSet, strongNames.ToArray());
}
private static PermissionSet GetPermissionSet(IPermission[] permissions)
{
var evidence = new Evidence();
evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
var result = SecurityManager.GetStandardSandbox(evidence);
foreach (var permission in permissions)
result.AddPermission(permission);
return result;
}
}
And let's see the test cases one by one
Case 1: ISerializable implementation
The same issue as in the question. The test passes if
InternalTypeReferenceAttribute is applied
sandbox is tried to be created multiple times (see the code)
or, if all the test cases are executed at once and this is not the first one
Otherwise, there comes the totally inappropriate Inheritance security rules violated while overriding member... exception when you instantiate SerializableCriticalClass.
[Test]
[SecuritySafeCritical] // for Activator.CreateInstance
public void SerializableCriticalClass_PartialTrustAccess()
{
var domain = CreateSandboxDomain(
new SecurityPermission(SecurityPermissionFlag.SerializationFormatter), // BinaryFormatter
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)); // Assert.IsFalse
var handle = Activator.CreateInstance(domain, Assembly.GetExecutingAssembly().FullName, typeof(Sandbox).FullName);
var sandbox = (Sandbox)handle.Unwrap();
try
{
sandbox.TestSerializableCriticalClass();
return;
}
catch (Exception e)
{
// without [InternalTypeReference] it may fail for the first time
Console.WriteLine($"1st try failed: {e.Message}");
}
domain = CreateSandboxDomain(
new SecurityPermission(SecurityPermissionFlag.SerializationFormatter), // BinaryFormatter
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)); // Assert.IsFalse
handle = Activator.CreateInstance(domain, Assembly.GetExecutingAssembly().FullName, typeof(Sandbox).FullName);
sandbox = (Sandbox)handle.Unwrap();
sandbox.TestSerializableCriticalClass();
Assert.Inconclusive("Meh... succeeded only for the 2nd try");
}
private partial class Sandbox
{
public void TestSerializableCriticalClass()
{
Assert.IsFalse(AppDomain.CurrentDomain.IsFullyTrusted);
// ISerializable implementer can be created.
// !!! May fail for the first try if the test does not use any internal type of the library. !!!
var critical = new SerializableCriticalClass();
// Critical method can be called via a safe method
critical.SafeEntryForCriticalCode();
// Critical method cannot be called directly by a transparent method
Assert.Throws<MethodAccessException>(() => critical.CriticalCode());
Assert.Throws<MethodAccessException>(() => critical.GetObjectData(null, new StreamingContext()));
// BinaryFormatter calls the critical method via a safe route (SerializationFormatter permission is required, though)
new BinaryFormatter().Serialize(new MemoryStream(), critical);
}
}
Case 2: Regular class with security critical members
The test passes under the same conditions as the first one. However, the issue is completely different here: a partially trusted code may access a security critical member directly.
[Test]
[SecuritySafeCritical] // for Activator.CreateInstance
public void CriticalClass_PartialTrustAccess()
{
var domain = CreateSandboxDomain(
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess), // Assert.IsFalse
new EnvironmentPermission(PermissionState.Unrestricted)); // Assert.Throws (if fails)
var handle = Activator.CreateInstance(domain, Assembly.GetExecutingAssembly().FullName, typeof(Sandbox).FullName);
var sandbox = (Sandbox)handle.Unwrap();
try
{
sandbox.TestCriticalClass();
return;
}
catch (Exception e)
{
// without [InternalTypeReference] it may fail for the first time
Console.WriteLine($"1st try failed: {e.Message}");
}
domain = CreateSandboxDomain(
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)); // Assert.IsFalse
handle = Activator.CreateInstance(domain, Assembly.GetExecutingAssembly().FullName, typeof(Sandbox).FullName);
sandbox = (Sandbox)handle.Unwrap();
sandbox.TestCriticalClass();
Assert.Inconclusive("Meh... succeeded only for the 2nd try");
}
private partial class Sandbox
{
public void TestCriticalClass()
{
Assert.IsFalse(AppDomain.CurrentDomain.IsFullyTrusted);
// A type containing critical methods can be created
var critical = new CriticalClass();
// Critical method can be called via a safe method
critical.SafeEntryForCriticalCode();
// Critical method cannot be called directly by a transparent method
// !!! May fail for the first time if the test does not use any internal type of the library. !!!
// !!! Meaning, a partially trusted code has more right than a fully trusted one and is !!!
// !!! able to call security critical method directly. !!!
Assert.Throws<MethodAccessException>(() => critical.CriticalCode());
}
}
Case 3-4: Full trust versions of case 1-2
For the sake of completeness here are the same cases as the ones above executed in a fully trusted domain. If you remove [assembly: AllowPartiallyTrustedCallers] the tests fail because then you can access critical code directly (as the methods are not transparent by default anymore).
[Test]
public void CriticalClass_FullTrustAccess()
{
Assert.IsTrue(AppDomain.CurrentDomain.IsFullyTrusted);
// A type containing critical methods can be created
var critical = new CriticalClass();
// Critical method cannot be called directly by a transparent method
Assert.Throws<MethodAccessException>(() => critical.CriticalCode());
// Critical method can be called via a safe method
critical.SafeEntryForCriticalCode();
}
[Test]
public void SerializableCriticalClass_FullTrustAccess()
{
Assert.IsTrue(AppDomain.CurrentDomain.IsFullyTrusted);
// ISerializable implementer can be created
var critical = new SerializableCriticalClass();
// Critical method cannot be called directly by a transparent method (see also AllowPartiallyTrustedCallersAttribute)
Assert.Throws<MethodAccessException>(() => critical.CriticalCode());
Assert.Throws<MethodAccessException>(() => critical.GetObjectData(null, default(StreamingContext)));
// Critical method can be called via a safe method
critical.SafeEntryForCriticalCode();
// BinaryFormatter calls the critical method via a safe route
new BinaryFormatter().Serialize(new MemoryStream(), critical);
}
Epilogue:
Of course, this will not solve your problem with .NET Fiddle. But now I would be very surprised if it wasn't a bug in the framework.
The biggest question to me now is the quoted part in the accepted answer. How did they come out with this nonsense? The ISafeSerializationData is clearly not a solution for anything: it is used exclusively by the base Exception class and if you subscribe the SerializeObjectState event (why isn't that an overridable method?), then the state will also be consumed by the Exception.GetObjectData in the end.
The AllowPartiallyTrustedCallers/SecurityCritical/SecuritySafeCritical triumvirate of attributes were designed for exactly the usage shown above. It seems total nonsense to me that a partially trusted code cannot even instantiate a type regardless of the attempt using its security critical members. But it is an even bigger nonsense (a security hole actually) that a partially trusted code may access a security critical method directly (see case 2) whereas this is forbidden for transparent methods even from a fully trusted domain.
So if your consumer project is a test or another well-known assembly, then the internal trick can be used perfectly. For .NET Fiddle and other real-life sandboxed environments the only solution is reverting back to SecurityRuleSet.Level1 until this is fixed by Microsoft.
Update: A Developer Community ticket has been created for the issue.
According to the MSDN see:
How to Fix Violations?
To fix a violation of this rule, make the GetObjectData method visible and overridable and make sure all instance fields are included in the serialization process or explicitly marked with the NonSerializedAttribute attribute.
The following example fixes the two previous violations by providing an overrideable implementation of ISerializable.GetObjectData on the Book class and by providing an implementation of ISerializable.GetObjectData on the Library class.
using System;
using System.Security.Permissions;
using System.Runtime.Serialization;
namespace Samples2
{
[Serializable]
public class Book : ISerializable
{
private readonly string _Title;
public Book(string title)
{
if (title == null)
throw new ArgumentNullException("title");
_Title = title;
}
protected Book(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
_Title = info.GetString("Title");
}
public string Title
{
get { return _Title; }
}
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Title", _Title);
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
GetObjectData(info, context);
}
}
[Serializable]
public class LibraryBook : Book
{
private readonly DateTime _CheckedOut;
public LibraryBook(string title, DateTime checkedOut)
: base(title)
{
_CheckedOut = checkedOut;
}
protected LibraryBook(SerializationInfo info, StreamingContext context)
: base(info, context)
{
_CheckedOut = info.GetDateTime("CheckedOut");
}
public DateTime CheckedOut
{
get { return _CheckedOut; }
}
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
protected override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("CheckedOut", _CheckedOut);
}
}
}
There are several questions on Stack Overflow that are similar but not exactly what I'm looking for. I would like to do Ninject binding based on a runtime condition, that isn't pre-known on startup. The other questions on Stack Overflow for dynamic binding revolve around binding based on a config file or some such - I need to it to happen conditionally based on a database value while processing the data for a particular entity. E.g.,
public class Partner
{
public int PartnerID { get; set; }
public string ExportImplementationAssembly { get; set; }
}
public interface IExport
{
void ExportData(DataTable data);
}
Elsewhere, I have 2 dlls that implement IExport
public PartnerAExport : IExport
{
private readonly _db;
public PartnerAExport(PAEntities db)
{
_db = db;
}
public void ExportData(DataTable data)
{
// export parter A's data...
}
}
Then for partner B;
public PartnerBExport : IExport
{
private readonly _db;
public PartnerBExport(PAEntities db)
{
_db = db;
}
public void ExportData(DataTable data)
{
// export parter B's data...
}
}
Current Ninject binding is;
public class NinjectWebBindingsModule : NinjectModule
{
public override void Load()
{
Bind<PADBEntities>().ToSelf();
Kernel.Bind(s => s.FromAssembliesMatching("PartnerAdapter.*.dll")
.SelectAllClasses()
.BindDefaultInterfaces()
);
}
}
So how do I set up the bindings such that I can do;
foreach (Partner partner in _db.Partners)
{
// pseudocode...
IExport exportModule = ninject.Resolve<IExport>(partner.ExportImplementationAssembly);
exportModule.ExportData(_db.GetPartnerData(partner.PartnerID));
}
Is this possible? It seems like it should be but I can't quite figure how to go about it. The existing binding configuration above works fine for static bindings but I need something I can resolve at runtime. Is the above possible or am I just going to have to bypass Ninject and load the plugins using old-school reflection? If so, how can I use that method to resolve any constructor arguments via Ninject as with the statically bound objects?
UPDATE: I've updated my code with BatteryBackupUnit's solution such that I now have the following;
Bind<PADBEntities>().ToSelf().InRequestScope();
Kernel.Bind(s => s.FromAssembliesMatching("PartnerAdapter.*.dll")
.SelectAllClasses()
.BindDefaultInterfaces()
.Configure(c => c.InRequestScope())
);
Kernel.Bind(s => s.FromAssembliesMatching("PartnerAdapter.Modules.*.dll")
.SelectAllClasses()
.InheritedFrom<IExportService>()
.BindSelection((type, baseTypes) => new[] { typeof(IExportService) })
);
Kernel.Bind<IExportServiceDictionary>().To<ExportServiceDictionary>().InSingletonScope();
ExportServiceDictionary dictionary = KernelInstance.Get<ExportServiceDictionary>();
Instantiating the export implementations within 2 test modules works and instantiates the PADBEntites context just fine. However, all other bindings in my services layer now no longer work for the rest of the system. Likewise, I cannot bind the export layer if I change PADBEntities variable/ctor argument to an ISomeEntityService component. It seems I'm missing one last step in configuring the bindings to get this work. Any thoughts?
Error: "Error activating ISomeEntityService. No matching bindings are available and the type is not self-bindable"
Update 2: Eventually got this working with a bit of trial and error using BatteryBackupUnit's solution though I'm not too happy with the hoops to jump thought. Any other more concise solution is welcome.
I changed the original convention binding of;
Kernel.Bind(s => s.FromAssembliesMatching("PartnerAdapter.*.dll")
.SelectAllClasses()
.BindDefaultInterfaces()
);
to the much more verbose and explicit;
Bind<IActionService>().To<ActionService>().InRequestScope();
Bind<IAuditedActionService>().To<AuditedActionService>().InRequestScope();
Bind<ICallService>().To<CallService>().InRequestScope();
Bind<ICompanyService>().To<CompanyService>().InRequestScope();
//...and so on for 30+ lines
Not my favorite solution but it works with explicit and convention based binding but not with two conventions. Can anyone see where I'm going wrong with the binding?
Update 3: Disregard the issue with the bindings in Update 2. It appears that I've found a bug in Ninject relating to having multiple binding modules in a referenced library. A change in module A, even though never hit via breakpoint will break a project explicitly using a different module B. Go figure.
It's important to note that while the actual "condition match" is a runtime condition, you actually know the possible set of matches in advance (at least on startup when building the container) - which is evidenced by the use of the conventions. This is what the conditional / contextual bindings are about (described in the Ninject WIKI and covered in several questions). So you actually don't need to do the binding at an arbitrary runtime-time, rather you just have to do the resolution/selection at an arbitrary time (resolution can actually be done in advance => fail early).
Here's a possible solution, which features:
creation of all bindings on startup
fail early: verification of bindings on startup (through instanciation of all bound IExports)
selection of IExport at an arbitrary runtime
.
internal interface IExportDictionary
{
IExport Get(string key);
}
internal class ExportDictionary : IExportDictionary
{
private readonly Dictionary<string, IExport> dictionary;
public ExportDictionary(IEnumerable<IExport> exports)
{
dictionary = new Dictionary<string, IExport>();
foreach (IExport export in exports)
{
dictionary.Add(export.GetType().Assembly.FullName, export);
}
}
public IExport Get(string key)
{
return dictionary[key];
}
}
Composition root:
// this is just going to bind the IExports.
// If other types need to be bound, go ahead and adapt this or add other bindings.
kernel.Bind(s => s.FromAssembliesMatching("PartnerAdapter.*.dll")
.SelectAllClasses()
.InheritedFrom<IExport>()
.BindSelection((type, baseTypes) => new[] { typeof(IExport) }));
kernel.Bind<IExportDictionary>().To<ExportDictionary>().InSingletonScope();
// create the dictionary immediately after the kernel is initialized.
// do this in the "composition root".
// why? creation of the dictionary will lead to creation of all `IExport`
// that means if one cannot be created because a binding is missing (or such)
// it will fail here (=> fail early).
var exportDictionary = kernel.Get<IExportDictionary>();
Now IExportDictionary can be injected into any component and just used like "required":
foreach (Partner partner in _db.Partners)
{
// pseudocode...
IExport exportModule = exportDictionary.Get(partner.ExportImplementationAssembly);
exportModule.ExportData(_db.GetPartnerData(partner.PartnerID));
}
I would like to do Ninject binding based on a runtime condition, that isn't pre-known on startup.
Prevent making runtime decisions during building of the object graphs. This complicates your configuration and makes your configuration hard to verify. Ideally, your object graphs should be fixed and should not change shape at runtime.
Instead, make the runtime decision at... runtime, by moving this into a proxy class for IExport. How such proxy exactly looks like, depends on your exact situation, but here's an example:
public sealed class ExportProxy : IExport
{
private readonly IExport export1;
private readonly IExport export2;
public ExportProxy(IExport export1, IExport export2) {
this.export1 = export1;
this.export2 = export2;
}
void IExport.ExportData(Partner partner) {
IExport exportModule = GetExportModule(partner.ExportImplementationAssembly);
exportModule.ExportData(partner);
}
private IExport GetExportModule(ImplementationAssembly assembly) {
if (assembly.Name = "A") return this.export1;
if (assembly.Name = "B") return this.export2;
throw new InvalidOperationException(assembly.Name);
}
}
Or perhaps you're dealing with a set of dynamically determined assemblies. In that case you can supply the proxy with a export provider delegate. For instance:
public sealed class ExportProxy : IExport
{
private readonly Func<ImplementationAssembly, IExport> exportProvider;
public ExportProxy(Func<ImplementationAssembly, IExport> exportProvider) {
this.exportProvider = exportProvider;
}
void IExport.ExportData(Partner partner) {
IExport exportModule = this.exportProvider(partner.ExportImplementationAssembly);
exportModule.ExportData(partner);
}
}
By supplying the proxy with a Func<,> you can still make the decision at the place where you register your ExportProxy (the composition root) where you can query the system for assemblies. This way you can register the IExport implementations up front in the container, which improves verifiability of the configuration. If you registered all IExport implementations using a key, you can do the following simple registration for the ExportProxy
kernel.Bind<IExport>().ToInstance(new ExportProxy(
assembly => kernel.Get<IExport>(assembly.Name)));
The default Global.asax.cs file from the "WCF REST Template 40(CS)" project template and every tutorial I've seen online include a variation of the following method:
private void RegisterRoutes()
{
// Edit the base address of Service1 by replacing the "Service1" string below
RouteTable.Routes.Add(new ServiceRoute("Service1", new WebServiceHostFactory(), typeof(Service1)));
}
Managing the service routing in this way seems needlessly cumbersome when the WebApplication itself should be able to discover which services should be available and apply routes based on convention or metadata.
QUESTIONS
Is there a built-in way beyond the default to define the service routes (either configurable in the web.config, or compiled onto the service itself)?
Do others that use this template always follow the model provided or has someone else come up with a better approach?
Proposed Solution
Migrated my proposed solution to an answer
I guess I have to assume that silence is acceptance. Here is my solution (originally from my question):
Assuming there is nothing better built in or otherwise available (because I didn't find anything), my attempt at doing this involves defining an attribute:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class ServiceRouteAttribute : Attribute
{
public string RoutePrefix { get; set; }
public Type ServiceFactoryType { get; set; }
public ServiceHostFactoryBase ServiceFactory
{
get
{
if (ServiceFactoryType == null || !ServiceFactoryType.IsRelated(typeof(ServiceHostFactoryBase)))
return null;
return Activator.CreateInstance(ServiceFactoryType) as ServiceHostFactoryBase;
}
}
public ServiceRouteAttribute() : this(string.empty) { }
public ServiceRouteAttribute(string routePrefix) : this(routePrefix, typeof(WebServiceHostFactory)) { }
public ServiceRouteAttribute(string routePrefix, Type serviceFactoryType)
{
RoutePrefix = routePrefix;
ServiceFactoryType = serviceFactoryType;
}
}
which is used to decorate each service contract that should be exposed, and changing the default RegisterRoutes to:
private void RegisterRoutes()
{
// `TypeHelper.GetTypes().FilterTypes<T>` will find all of the types in the
// current AppDomain that:
// - Implement T if T is an interface
// - Are decorated with T if T is an attribute
// - Are children of T if T is anything else
foreach (var type in TypeHelper.GetTypes()
.FilterTypes<ServiceRouteAttribute>())
{
// routeAttrs should never be null or empty because only types decorated
// with `ServiceRouteAttribute` should ever get here.
// `GetAttribute<T>` is my extension method for `MemberInfo` which returns all
// decorations of `type` that are T or children of T
var routeAttrs = type.GetAttributes<ServiceRouteAttribute>();
foreach (var routeAttr in routeAttrs)
{
// Some dupe and error checking
var routePrefix = routeAttr.RoutePrefix;
if (string.IsNullOrEmpty(routePrefix))
routePrefix = type.Name;
RouteTable.Routes.Add(new ServiceRoute(routePrefix,
routeAttr.ServiceFactory,
type));
}
}
}
This seems to work and isn't too intrusive because it only happens at Application_Start, but I'm new to building RESTful web services with WCF4 so I don't know what sort of problems it could cause.
If anyone comes up with a more elegant way of solving this, I'd gladly consider any alternative.