Autofac - Resolve specific implementation from registered assembly - vb.net

I'm using Autofac and want to resolve the correct implementation of the current assembly
I have a DataContextFactory Interface and Class:
Public Interface IDataContextFactory
Inherits IDisposable
Function GetDataContext() As IDataContext
End Interface
and the Implementation of the Interface
Public Class CDataContextFactory
Implements IDataContextFactory
Private m_oDbContext As IDataContext
Public Sub New(ByVal i_oDbContext As IDataContext)
m_oDbContext = i_oDbContext
End Sub
Public Function GetDataContext() As CoreData.IDataContext Implements CoreData.IDataContextFactory.GetDataContext
Return m_oDbContext
End Function
End Class
So now I have in every registered assembly different IDataContext Implementations. For example I have an assembly called ReportData with the data context
Public Class CReportDataContext
Inherits DbContext
Implements IDataContext
---
End Class
And also one implementation inside an other Assembly CommonData
Public Class CFacadeDataContext
Implements IDataContext
---
End Class
Then I have in every Assembly an implementation of my IRepository. For example
Public MustInherit Class CBaseReadRepository(Of T As {IEntity, Class})
Implements IReadRepository(Of T)
Private m_oDataContextFactory As IDataContextFactory
Private m_oDataContext As IDataContext
Protected ReadOnly m_oObjectDataSet As CQuery(Of T)
Public Sub New(ByVal i_oDataContextFactory As IDataContextFactory)
m_oDataContextFactory = i_oDataContextFactory
m_oObjectDataSet = DataContext.ObjectDataSet(Of T)()
End Sub
----
End Class
So how can I solve that the DataContextFactory will resolve the CReportDataContext inside the Assembly ReportData and the CFacadeDataContext inside the Assembly CommonData
Here is my ContainerBuilder registration:
Dim builder As New ContainerBuilder()
Dim oData = Assembly.Load("ReportData")
builder.RegisterAssemblyTypes(oData).Where(Function(t) t.Name.EndsWith("DataContext")).As(Of IDataContext) _
.AsImplementedInterfaces.SingleInstance
oData = Assembly.Load("CommonData")
builder.RegisterAssemblyTypes(oData).Where(Function(t) t.Name.EndsWith("DataContext")) _
.AsImplementedInterfaces().SingleInstance
builder.RegisterAdapter(Of IDataContext, IDataContextFactory)(Function(x) New CDataContextFactory(x))
Thanks

Autofac doesn't have built-in support for this sort of use case. Generally it's recommended that you try not to tie specific implementations to consumers because that breaks the whole IoC pattern - you may as well "new-up" the dependency type you need right in the class rather than injecting it.
If you absolutely must tie them together, you only have a couple of options. Neither is pretty, and both will require you to change the way you register things - you may not be able to do the RegisterAssemblyTypes assembly scanning like you do now.
First, you could use named registrations. When you register your IDataContext, you give it a name. When you register your consuming class, you tell the builder which named instance you expect to use.
builder.RegisterType<MyDataContext>().Named<IDataContext>("some-name");
var contextParam = ResolvedParameter.ForNamed<IDataContext>("some-name");
builder.RegisterType<MyConsumer>().As<IConsumer>().WithParameter(contextParam);
Second, you could register an expression rather than a type for the consumer:
builder.Register(c => new Consumer(new SomeContext())).As<IConsumer>();
Finally, you could create a special module that does the work of figuring out which assembly the consumer is coming from and try to match it to a corresponding IDataContext. This is more "automatic" but is a lot more complex. A stub might look like this:
public class DataContextModule : Autofac.Module
{
protected override void AttachToComponentRegistration(
IComponentRegistry componentRegistry,
IComponentRegistration registration)
{
registration.Preparing += OnComponentPreparing;
}
public static void OnComponentPreparing(object sender, PreparingEventArgs e)
{
Type typeBeingResolved = e.Component.Activator.LimitType;
// TODO: Do some reflection to determine if the type takes an IDataContext
// in the constructor. If it doesn't, bail. If it does...
var parameter = new ResolvedParameter(
(p, i) => p.ParameterType = typeof(IDataContext),
(p, i) => {
// TODO: Use i (the IComponentContext for the resolution)
// to locate the right IDataContext from the list of registrations,
// resolve that one, and return it so it can be used in
// constructing the consumer object.
});
}
}
Like I said, not pretty.
If you have the ability to influence your design, it might be easier to make marker interfaces, like:
public interface ICoreDataContext : IDataContext { }
And then in your constructors take the specific interface:
public SomeClass(ICoreDataContext context);
That way type resolution would just work. (Marker interfaces aren't the greatest pattern in the world, either, but it's arguably better than tying individual implementations of things to specific consuming types.)

Related

VB.NET access level of interface declaration not matching access level of implementation [duplicate]

Interface behaves differently in Vb.Net. Below is a sample code snippet where IStudent interface has a method SayHello which is implemented by a class Student. The Access modifier for SayHello should be Public by default. By changing Access modifier to Private is not breaking the existing code and still i can access this private method using below code
Dim stdnt As IStudent = New Student
stdnt.SayHello()
Access modifier determines the scope of the members in a class, more over private members are accessible only from the class which exists. But here the theory of Access Modifier, Encapsulation are broken.
Why .net has designed in this way?
Is the concept of Access modifier and encapsulation are really broken?
How .net framework internally handle this situation?
Thanks in advance
Module Module1
Sub Main()
Dim stdnt As IStudent = New Student
stdnt.Name = "vimal"
stdnt.SayHello()
End Sub
End Module
Public Interface IStudent
Property Name As String
Sub SayHello()
End Interface
Public Class Student
Implements IStudent
Private Property Name As String Implements IStudent.Name
Private Sub SayHello() Implements IStudent.SayHello
Console.WriteLine("Say Hello!")
End Sub
End Class
The original poster submitted this question to me via TheBugGuys#Coverity.com; my answer is here:
https://communities.coverity.com/blogs/development-testing-blog/2013/10/09/oct-9-posting-interface-behaves-differently-in-visual-basic
To briefly summarize:
Why was .NET designed in this way?
That question is impossibly vague.
Is encapsulation broken by explicit implementation in C# and VB?
No. The privacy of the method restricts the accessibility domain of the methods name, not who can call the method. If the author of the class chooses to make a private method callable by some mechanism other than looking it up by name, that is their choice. A third party cannot make the choice for them except via techniques such as private reflection, which do break encapsulation.
How is this feature implemented in .NET?
There is a special metadata table for explicit interface implementations. The CLR consults it first when attempting to figure out which class (or struct) method is associated with which interface method.
From MSDN:
You can use a private member to implement an interface member. When a private member implements a member of an interface, that member becomes available by way of the interface even though it is not available directly on object variables for the class.
In C#, this behaviour is achieved by implementing the interface explicitly, like this:
public interface IStudent {
string Name { get; set; }
void SayHello();
}
public class Student : IStudent {
string IStudent.Name { get; set; }
void IStudent.SayHello() {
Console.WriteLine("Say Hello!");
}
}
So, if you were to omit the IStudent. in front of the method names, it would break. I see that in the VB syntax the interface name is included. I don't know whether this has any implications altough. But interface members aren't private, since the interface isn't. They're kinda public...
There is no fundamental difference between C# and VB.NET, they just chose different ways to solve ambiguity. Best demonstrated with a C# snippet:
interface ICowboy {
void Draw();
}
interface IPainter {
void Draw();
}
class CowboyPainter : ICowboy, IPainter {
void ICowboy.Draw() { useGun(); }
void IPainter.Draw() { useBrush(); }
// etc...
}
VB.NET just chose consistent interface implementation syntax so the programmer doesn't have to weigh the differences between implicit and explicit implementation syntax. Simply always explicit in VB.NET.
Only the accessibility of the interface method matters. Always public.
When your variable stdnt is declared as IStudent, the interface methods and properties are then made Public, so the derived class' (Student) implementation is executed. If, on the other hand, if stdnt was declared as Student, the private members (Name and SayHello) would not be implemented, and an error would be thrown.
I'm guessing that the Interface members stubs (Name & SayHello) are by default Public, and the access modifier definitions of the derived class' implementation are ignored.
IMHO.
The exact equivalent in C# is the following - the method available to objects of the interface type and the private method available otherwise:
void IStudent.SayHello()
{
this.SayHello();
}
private void SayHello()
{
Console.WriteLine("Say Hello!");
}

How to inject dependencis into WCF Attribute with Simple Injector

I have a bunch of WCF services that works with REST and SOAP. I have created an WCF attribute who checks if the current httpcontext exists, if exists it use cookie authentication, other way it use custom WCF authentication.
My attribute looks like this:
Public Class AuthRequired
Inherits Attribute
Implements IOperationBehavior, IParameterInspector
Public Sub AddBindingParameters(operationDescription As OperationDescription, bindingParameters As Channels.BindingParameterCollection) Implements IOperationBehavior.AddBindingParameters
End Sub
Public Sub ApplyClientBehavior(operationDescription As OperationDescription, clientOperation As ClientOperation) Implements IOperationBehavior.ApplyClientBehavior
End Sub
Public Sub ApplyDispatchBehavior(operationDescription As OperationDescription, dispatchOperation As DispatchOperation) Implements IOperationBehavior.ApplyDispatchBehavior
dispatchOperation.ParameterInspectors.Add(Me)
End Sub
Public Sub Validate(operationDescription As OperationDescription) Implements IOperationBehavior.Validate
End Sub
Public Sub AfterCall(operationName As String, outputs() As Object, returnValue As Object, correlationState As Object) Implements IParameterInspector.AfterCall
End Sub
Public Function BeforeCall(operationName As String, inputs() As Object) As Object Implements IParameterInspector.BeforeCall
' IDS is the custom authentication service.
If IDS.Usuario Is Nothing Then
If HttpContext.Current Is Nothing Then
Throw New SecurityException("Las credenciales no son válidas para esta operación o no fueron provistas.")
Else
Throw New WebFaultException(Of String)("ACCESO DENEGADO. REVISE SUS CREDENCIALES.", Net.HttpStatusCode.Forbidden)
End If
End If
End Function
End Class
So, my question is how can I inject dependencies into this attribute using Simple Injector? I google for a while but the only thing I found was for Ninject, or inject filters on WebAPI.
Cheers!
You can't do constructor injection into attributes, because it is the CLR who is in control over the creation of attributes; not the DI library. Although you could initialize/build-up attributes after they have been created and inject dependencies using property injection, this is very risky for the following reasons:
Many frameworks cache attributes, which make them effectively singletons. This will cause Captive Dependencies in cases the dependencies themselves aren't singletons themselves.
It will be hard to impossible to let the container verify object graphs that start from the attributes, which might cause a false sense of security when verifying and diagnosing the container's configuration.
Instead, a much better approach is to either make attributes either passive or humble objects.
With a humble object, you extract all logic out of the attribute into its own service. The only code that will be left in the attribute is a call to your container or Service Locator to resolve that service and you call the method. This might look like this (excuse my C#):
public class AuthRequiredAttribute : Attribute, IOperationBehavior
{
public object BeforeCall(string operationName, object[] inputs) {
var checker = Global.Container.GetInstance<IAuthorizationChecker>();
checker.Check();
}
}
// Attribute's logic abstracted to a new service. This service can be
// registered, verified, diagnosed, and tested.
public class AuthorizationChecker : IAuthorizationChecker
{
private readonly IDS authenticationService;
public AuthorizationChecker(IDS authenticationService) {
this.authenticationService = authenticationService;
}
public void Check() {
if (this.authenticationService.Usuario == null) {
if (HttpContext.Current == null) {
throw new SecurityException();
} else {
throw new WebFaultException<string>();
}
}
}
}
This requires you to expose the container in a way that your attributes can resolve the services they need. Advantage of this is that it is easy implemented, quite clean. Downside is that that you have to fall back to the Service Locator anti-pattern to get this working, and you have to make sure that your service is registered, because the container won't warn about this and this will, therefore, fail at runtime instead of during application startup of inside an integration test that calls container.Verify().
The second option is using passive attributes. This is especially useful when you have multiple of these attributes. This article describes the basic idea behind passive attributes and gives an example how to implement this in Web API. WCF has different interception points, so applying this to WCF requires a different implementation, but the concept stays the same.

Interface behavior is dfferent in VB.Net

Interface behaves differently in Vb.Net. Below is a sample code snippet where IStudent interface has a method SayHello which is implemented by a class Student. The Access modifier for SayHello should be Public by default. By changing Access modifier to Private is not breaking the existing code and still i can access this private method using below code
Dim stdnt As IStudent = New Student
stdnt.SayHello()
Access modifier determines the scope of the members in a class, more over private members are accessible only from the class which exists. But here the theory of Access Modifier, Encapsulation are broken.
Why .net has designed in this way?
Is the concept of Access modifier and encapsulation are really broken?
How .net framework internally handle this situation?
Thanks in advance
Module Module1
Sub Main()
Dim stdnt As IStudent = New Student
stdnt.Name = "vimal"
stdnt.SayHello()
End Sub
End Module
Public Interface IStudent
Property Name As String
Sub SayHello()
End Interface
Public Class Student
Implements IStudent
Private Property Name As String Implements IStudent.Name
Private Sub SayHello() Implements IStudent.SayHello
Console.WriteLine("Say Hello!")
End Sub
End Class
The original poster submitted this question to me via TheBugGuys#Coverity.com; my answer is here:
https://communities.coverity.com/blogs/development-testing-blog/2013/10/09/oct-9-posting-interface-behaves-differently-in-visual-basic
To briefly summarize:
Why was .NET designed in this way?
That question is impossibly vague.
Is encapsulation broken by explicit implementation in C# and VB?
No. The privacy of the method restricts the accessibility domain of the methods name, not who can call the method. If the author of the class chooses to make a private method callable by some mechanism other than looking it up by name, that is their choice. A third party cannot make the choice for them except via techniques such as private reflection, which do break encapsulation.
How is this feature implemented in .NET?
There is a special metadata table for explicit interface implementations. The CLR consults it first when attempting to figure out which class (or struct) method is associated with which interface method.
From MSDN:
You can use a private member to implement an interface member. When a private member implements a member of an interface, that member becomes available by way of the interface even though it is not available directly on object variables for the class.
In C#, this behaviour is achieved by implementing the interface explicitly, like this:
public interface IStudent {
string Name { get; set; }
void SayHello();
}
public class Student : IStudent {
string IStudent.Name { get; set; }
void IStudent.SayHello() {
Console.WriteLine("Say Hello!");
}
}
So, if you were to omit the IStudent. in front of the method names, it would break. I see that in the VB syntax the interface name is included. I don't know whether this has any implications altough. But interface members aren't private, since the interface isn't. They're kinda public...
There is no fundamental difference between C# and VB.NET, they just chose different ways to solve ambiguity. Best demonstrated with a C# snippet:
interface ICowboy {
void Draw();
}
interface IPainter {
void Draw();
}
class CowboyPainter : ICowboy, IPainter {
void ICowboy.Draw() { useGun(); }
void IPainter.Draw() { useBrush(); }
// etc...
}
VB.NET just chose consistent interface implementation syntax so the programmer doesn't have to weigh the differences between implicit and explicit implementation syntax. Simply always explicit in VB.NET.
Only the accessibility of the interface method matters. Always public.
When your variable stdnt is declared as IStudent, the interface methods and properties are then made Public, so the derived class' (Student) implementation is executed. If, on the other hand, if stdnt was declared as Student, the private members (Name and SayHello) would not be implemented, and an error would be thrown.
I'm guessing that the Interface members stubs (Name & SayHello) are by default Public, and the access modifier definitions of the derived class' implementation are ignored.
IMHO.
The exact equivalent in C# is the following - the method available to objects of the interface type and the private method available otherwise:
void IStudent.SayHello()
{
this.SayHello();
}
private void SayHello()
{
Console.WriteLine("Say Hello!");
}

Using Ninject to bind an interface to multiple implementations unknown at compile time

I just recently started using Ninject (v2.2.0.0) in my ASP.NET MVC 3 application. So far I'm thrilled with it, but I ran into a situation I can't seem to figure out.
What I'd like to do is bind an interface to concrete implementations and have Ninject be able to inject the concrete implementation into a constructor using a factory (that will also be registered with Ninject). The problem is that I'd like my constructor to reference the concrete type, not the interface.
Here is an example:
public class SomeInterfaceFactory<T> where T: ISomeInterface, new()
{
public T CreateInstance()
{
// Activation and initialization logic here
}
}
public interface ISomeInterface
{
}
public class SomeImplementationA : ISomeInterface
{
public string PropertyA { get; set; }
}
public class SomeImplementationB : ISomeInterface
{
public string PropertyB { get; set; }
}
public class Foo
{
public Foo(SomeImplementationA implA)
{
Console.WriteLine(implA.PropertyA);
}
}
public class Bar
{
public Bar(SomeImplementationB implB)
{
Console.WriteLine(implB.PropertyB);
}
}
Elsewhere, I'd like to bind using just the interface:
kernel.Bind<Foo>().ToSelf();
kernel.Bind<Bar>().ToSelf();
kernel.Bind(typeof(SomeInterfaceFactory<>)).ToSelf();
kernel.Bind<ISomeInterface>().To ...something that will create and use the factory
Then, when requesting an instance of Foo from Ninject, it would see that one of the constructors parameters implements a bound interface, fetch the factory, and instantiate the correct concrete type (SomeImplementationA) and pass it to Foo's constructor.
The reason behind this is that I will have many implementations of ISomeInterface and I'd prefer to avoid having to bind each one individually. Some of these implementations may not be known at compile time.
I tried using:
kernel.Bind<ISomeInterface>().ToProvider<SomeProvider>();
The provider retrieves the factory based on the requested service type then calls its CreateInstance method, returning the concrete type:
public class SomeProvider : Provider<ISomeInterface>
{
protected override ISomeInterface CreateInstance(IContext context)
{
var factory = context.Kernel.Get(typeof(SomeInterfaceFactory<>)
.MakeGenericType(context.Request.Service));
var method = factory.GetType().GetMethod("CreateInstance");
return (ISomeInterface)method.Invoke();
}
}
However, my provider was never invoked.
I'm curious if Ninject can support this situation and, if so, how I might go about solving this problem.
I hope this is enough information to explain my situation. Please let me know if I should elaborate further.
Thank you!
It seems you have misunderstood how ninject works. In case you create Foo it sees that it requires a SomeImplementationA and will try to create an instance for it. So you need to define a binding for SomeImplementationA and not for ISomeInterface.
Also most likely your implementation breaks the Dependency Inversion Princple because you rely upon concrete instances instead of abstractions.
The solution to register all similar types at once (and the prefered way to configure IoC containers) is to use configuration by conventions. See the Ninject.Extensions.Conventions extenstion.

Use of static local variables in lazy loading property in VB.NET

I just recently learned about the uses of static local variables in VB.NET and wondered about it's potential use in lazy loading properties.
Consider the following example code.
Public Class Foo
Implements IFoo
End Class
Public Interface IFoo
End Interface
Public Class Bar
Private _fooImplementation As IFoo
Public ReadOnly Property FooImplementation As IFoo
Get
If _fooImplementation Is Nothing Then _fooImplementation = New Foo
Return _fooImplementation
End Get
End Property
End Class
This would be a usual, simplified lazy-loading property. You may even want to use the generic Lazy Class to get (as far as i know) the same behaviour.
Now, let's look at the property while using a static variable.
Public Class Bar
Public ReadOnly Property FooImplementation As IFoo
Get
Static _fooImplementation as IFoo = New Foo
Return _fooImplementation
End Get
End Property
End Class
As far as i can see, this has a few advantages over the usual implementation, primary your inability to access the variable outside of the property, as well as not having to use an additional variable.
My question to you is: Which of those is the "right" way to do it? I know that static variables have additional overhead, but is it bad enough to create, in my personal opinion, unclearer code that can be misused easier? How much performance do you lose compared to the "traditional" method? How does it matter for small classes compared to huge factories?
Thanks in advance.
The Static keyword has rather a lot of overhead, the compiler generates a big chunk of IL to implement it. What it does do that your 1st snippet doesn't do is ensure that threading doesn't cause problems. If that is not a concern then your 1st snippet is a lot cheaper. Not just because it has a lot less IL but also because it will be inlined. A getter with Static will never be inlined since it contains Try/Finally code.
If you are targeting .NET 4 then you definitely should take a look at the Lazy(Of T) class.
That question was interesting enough for me to find the answer...how exactly does VB.NET implement static. Here's a C# equivilent:
public class Bar
{
[SpecialName]
private IFoo \u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation;
[SpecialName]
private StaticLocalInitFlag \u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init;
public IFoo FooImplementation
{
get
{
Monitor.Enter((object) this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init);
try
{
if ((int) this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init.State == 0)
{
this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init.State = (short) 2;
this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation = (IFoo) new Foo();
}
else if ((int) this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init.State == 2)
throw new IncompleteInitialization();
}
finally
{
this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init.State = (short) 1;
Monitor.Exit((object) this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init);
}
return this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation;
}
}
[DebuggerNonUserCode]
public Bar()
{
this.\u0024STATIC\u0024get_FooImplementation\u0024200122C\u0024_fooImplementation\u0024Init = new StaticLocalInitFlag();
}
}