how can we call ninjects service locator in code? - asp.net-mvc-4

first time on stackoverflow + ninject (IoC's)
I have a situation in which I have Business Objects Implemented in a way that they have Models in them... i.e.
Public Class Whatever
Implements IWhatEver
Public Property Id as Integer
Public Property Name as String
Public Function SetWhatEver() as Whatever
'Do Whatever Settings
End Function
End Class
I am using ninject for DI (Dependency Injection) however the issue was that I couldn't use an Interface as a model being passed in an action, therefore I am trying to make a custom modelbinder and want to use the bindingContext.ModelType to pass to ninject and ninject to resolve it for me and so I can do my binding with metadata
Public Overrides Function BindModel(controllerContext As ControllerContext, bindingContext As ModelBindingContext) As Object
Dim modelType = ninjectPleaseResolve(bindingContext.ModelType)
Dim metaData = ModelMetadataProviders.Current.GetMetadataForType(Nothing, modelType)
bindingContext.ModelMetadata = metadata
Return MyBase.BindModel(controllerContext, bindingContext)
End Function
I hope this makes sense... I have tried looking for answers BTW and nothing online is making sense to me, so please can you explain in simple terms..
EDIT
I am adding the controller code below to give you a better understanding of what I am trying to do.. I don't want to use the Whatever class instead I want to use the IWhatever in the controller for my processing... please see below an example...
Public Class MainController
Inherits System.Web.Mvc.Controller
Dim repository As IWhatever
Public Sub New(pWhatever As IWhatever)
repository = pWhatever
End Sub
Function Index(myValues As IWhatever) As ActionResult
'So I can process these values to my liking...
repository.SetWhatEver(myValues)
' and then perhaps other functions like...
repository.Save()
Return View()
End Function
I hope this makes a little sense now..

the issue was that I couldn't use an Interface as a model being passed
in an action
You shouldn't pass in services through the action method. You should pass services in through the constructor. This way your container can build up the controller and all related objects for you and this way you don't have to write a custom model binder.

Related

Named Constructor Idiom in VB.NET?

Is using the Named Constructor Idiom possible in VB.NET? I've found many examples in C#/C++ but can't quite wrap my head around how to use it in vb.net. Seems like a better method of keeping my code readable when involving a lot of constructors with similar argument types.
I've never heard this term before, but after a quick search it sounds vaguely like the Static Factory Pattern. The idea is you make the constructor private and use a shared (static in c#) public function to create the new object.
Public Class Foo
Private Sub New()
End Sub
Public Shared Function CreateNew(param as Object) as Foo
Dim obj as New Foo()
obj.Prop = param
return obj
End Function
End Class
You sure can make Named Constructors in VB. The pattern uses a static (Shared in VB) factory method on the class itself, so that the method can be named. (Other Factory patterns involve using a separate Factory class to provide the static method.)
System.Drawing.Color is a simple example. The pattern is implemented underneath as a static (Shared) property. Since no arguments are necessary, the Get method of a Property works just fine:
Public Shared ReadOnly Property Chartreuse As Color
Usage:
Dim favoriteColor as Color = Color.Chartreuse
Or you can make static factory methods to do the same thing.
Public Class TheClass
Public Sub New()
End Sub
Public Sub New(input As String)
'do something with input
End Sub
Public Shared Function MyNamedConstructor() As TheClass
Return New TheClass
End Function
Public Shared Function AnotherNamedConstructor() As TheClass
Return New TheClass("Another Name")
End Function
End Class
As for whether this pattern is "better" than overloading constructors, that's really an opinion. Personally, I would just overload the constructors. As you can see in the example above, the constructors need to be there anyway.
I suggest using the Named Constructor pattern when you have only a few possible ways to construct your class/struct, but consumers of your class/struct will be using those few constructors often, and with different input values to those constructors (as in the System.Drawing.Color example).
The Name in 'Named Constructor' doesn't represent a name for the constructor itself, but for the object resulting from the constructor. If your named constructor can be used to create two objects that don't feel right to give the same name to, then don't give the constructor that name.

InvalidCastException when passing a mocked dependency into a function

I am using Rhino Mocks along with nUnit to attempt to test my function IsApprovable() on an object. The function I am testing relies on another object "UserManager" that needs to be passed in. I am attempting to mock an instance of UserManager so I can specify the result of another function GetApproverDependantsList()
My issue is that when I mock the object and pass it into the function I am testing I get the following InvalidCastException:
Unable to cast object of type 'Castle.Proxies.IUserManagerProxye15b431a53ca4190b7ffbdf5e241e2bb' to type 'MyNamespace.Users.UserManager'.
I am new to this so I am not really sure if I am doing things correctly... Here is the sample mocking code I am using:
Dim helper As New BookingManagerHelper()
Dim booking As Booking = GetDummyBooking() 'method to get a booking in suitable state
Dim parameters As Collection(Of Parameter) = GetDummyParameters() 'factory method, as above
Dim mockedUserManager = MockRepository.GenerateMock(Of Users.IUserManager)()
'I have created a dummy function called GetUserCollectionWithDependant() to create the results I need the mocked function to return...
mockedUserManager.Stub(Function(x) x.GetApproverDependantsList(-1)).[Return](GetUserCollectionWithDependant(1))
'It's the line below where I find my exception...
Assert.AreEqual(True, helper.IsApprovable(booking, mockedUserManager, parameters))
The function I am attempting to test looks like the following:
Public Function IsApprovable(ByVal Booking As Booking , ByVal UserManager As Users.UserManager, Optional ByVal Parameters As Collection(Of Parameter) = Nothing) As Boolean
'various logic checks are performed on the objects passed in
End Function
Some things to note:
UserManager implements the interface IUserManager
UserManager contains additional properties and functions that are not defined by the interface
UserManager also inherits from a base class (do I need to override base properties?)
I can post more code if needed. Thanks in advance.
I am no expert in VB.NET but IsApprovable expects a UserManager instance. The mock is of type IUserManager. Maybe you want to adjust IsApprovable to use a IUserManager instance.

Breaking BLL (Business Logic Layer) to BLL and DAL (Data Access Layer)

Please see the code below:
Imports Microsoft.VisualBasic
Public Class PersonBLL
Private Name As String
Private Age As Integer
Dim objPersonDAL As New PersonDAL
Dim objPerson As Person
Public Sub getPersonByID()
objPerson = objPersonDAL.getPersonByID()
MsgBox(objPerson.Name)
End Sub
End Class
Public Class PersonDAL
Private Name As String
Private Age As Integer
Public Function getPersonByID() As Person
'Connect to database and get Person. Return a person object
Dim p1 As New Person
p1.Name = "Ian"
p1.Age = 30
Return p1
End Function
End Class
Public Class Person
Private _Name As String
Private _Age As Integer
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Public Property Age() As Integer
Get
Return _Age
End Get
Set(ByVal value As Integer)
_Age = value
End Set
End Property
End Class
PersonBLL calls PersonDAL and returns a Person object. Is this the correct approach? i.e. I have identified a persistent class and created a corresponding DAL class with a function for accessing the data and returning the Person object.
There is a comment that states that this question is "subjective". I agree with this. I realise that the design depends on the requirements of the project. Are there any principles documented for designing a DAL similar to SOLID (single responsibility etc) etc.
Yes, your question demonstrates a very clean way to separate the logic into layers. The PersonBLL class would be part of the business layer, the PersonDAL class would be part of the data access layer, and the Person class would be part of the data transfer objects (DTO) layer. This is a very common way to separate your layers which works well in many situations.
My only recommendations would be:
You should put each layer in their own namespaces, if not also their own class library projects.
You should not show a message box from the business layer. I assume you only did this as a means of demonstration, but just in case, I thought I should mention it. Showing a message box should be part of the UI layer. For instance, if you were calling PersonBLL.getPersonByID from a windows service or a web service, showing a message box would be entirely inappropriate.
Typically, all methods are PascalCase, not camelCase. Some people prefer to make private methods camel case, but certainly public methods shouldn't be camel case.
Consider using dependency-injection techniques (DI) to inject the data access object into the business object.
Dependency Injection
Here's an example of how to do this with DI techniques:
Public Class BusinessFactory
Public Function NewPersonBusiness() As IPersonBusiness
Return New PersonBusiness(New PersonDataAccess())
End Function
End Class
Public Class PersonBusiness
Implements IPersonBusiness
Public Sub New(personDataAccess As IPersonDataAccess)
_personDataAccess = personDataAccess
End Sub
Private _personDataAccess As IPersonDataAccess
Public Function GetPersonByID() As PersonDto Implements IPersonBusiness.GetPersonByID
Return _personDataAccess.GetPersonByID()
End Sub
End Class
Public Interface IPersonBusiness
Function GetPersonByID() As PersonDto
End Interface
Public Interface IPersonDataAccess
Function GetPersonById() As PersonDto
End Interface
Public Class PersonDto
Private _name As String
Private _age As Integer
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property Age() As Integer
Get
Return _age
End Get
Set(ByVal value As Integer)
_age = value
End Set
End Property
End Class
Doing it this way has many advantages. You can have multiple interchangeable data access layer implementations, so it's more flexible. Also, you can inject a fake data access object when you want to unit test the business class. DI design avoids many of the traps that lead to buggy, spaghetti code.
With DI, it is typically recommended that you ask for dependency objects as an interface rather than as a concrete type (e.g. IPersonDataAccess rather than PersonDataAccess). Doing so can be a little bit of a hassle, but you get use to it quickly. Since you are often, at that point, creating one interface for every class, it's convenient to just put the interface in the same code file as the class. So, for instance, PersonBusiness.vb would contain both the PersonDataAccess class and the IPersonDataAccess interface.
There are two reasons why using interfaces, rather than classes, for your dependencies is important:
It ensures that the design is flexible. You want to be able to override every public member of the dependency type so that you can create any kind of concrete implementation. There are other ways to do this. For instance, you could skip creating the IPersonDataAcess interface by simply marking every public property and method in the PersonDataAccess class with the Overrideable modifier, but there's nothing forcing you to do that. Even if you always remembered to do so, that doesn't mean someone else working on your code would know they should do that.
DI is often tied-in with unit testing because it is the best tool available for ensuring that code is testable. When unit testing, it is particularly important that you are able to override ever member in a dependency type so you can make a "fake" object that works just the way you need it to work in order to properly perform the unit test. These "fake" objects are called mocks.
You are being more technically honest about what your dependency is. In reality, you aren't really saying that your dependency is actually an instance of the PersonDataAccess class. In actuality, your dependency is any object that happens to have that same public interface. By asking for the class, you are implying that you need a particular implementation, which is a lie. If you have designed it properly, you only care about the interface being the same, so by asking only for the interface itself, you are specifying precisely what you mean to specify :)

asp.net c# Automap a class from within that class

To best describe what I want to happen, i'll show what i'm doing, as to me it makes sense that this would work ...
public class foo()
{
public foo()
{
MyContext db = new MyContext();
foobar = db.foobar.first();
this = Mapper.Map<bar, foo>(foobar);
}
}
Basically, I want to use automapper within the destination class to map from the source class within the destination classes constructor.
Is there a way to do this?
You cannot do this because this is read only in C#. You cannot assign this a value in the constructor. Not cool to try to change the reference of an object in its constructor. You will have to do the mapping manually and assign each individual property. I would also question if it as a good practice to assign an object values from a database or service in a default constructor. It is not very transparent to the user of the object what is going on and you can get an exception in your constructor.

Factory method for generics in VB.NET

I want to create a factory for generic classes in VB.NET and I am running into issues.
What I have are two interfaces:
IPersistentObject and IPManagerBase(Of T as IPersistentObject)
The logic is that for each type of peristent object I have a corresponding manager class handling query logic.
Now I have a base class like this:
public class PManagerBase(Of T as IPersistentObject) Implements IPManagerBase(of T)
So, now in the real world I have a persistent type "PUser" and a corresponding manager declared like this:
public class PUserManager implements PManagerBase(Of PUser)
I have about 100 of those persistent objects and corresponding manager classes.
Now I want to have a factory, which I would invoke like this (removing the details):
MyFactory.CreateManager<PUserManager>()
I am creating my Factory like this
public class MyFactory
public shared function CreateManager(Of T as {PManagerBase(Of IPersistentObject), New}) as T
return new T()
end function
end class
Looks great.
Now I want to invoke it:
Dim myManager = MyFactory.CreateManager<PUserManager>()
What happens?
I get a compile error: "PUserManager does not implement/inherit PManagerBase(Of IPersistentObject)". I get the message in German so this is a free tranlation.
What would I need to change to make this running?
It works if I declare my factory like this:
public class MyFactory
public shared function CreateManager(Of T as {PManagerBase(Of PUser), New}) as T
return new T()
end function
end class
But then the benefit is gone, since it works only for Managers of the PUser object.
A better solution is
public class MyFactory
public shared function CreateManager(Of T as {PManagerBase(Of U), New}, U as IPersistentObject) as T
return new T()
end function
end class
This works, but I have to call my factory method like this now:
Dim myManager = MyFactory.CreateManager<PUserManager, PUser>()
I don't like this since this is redundant and I don't need U at all in the function. In it's declaration PUserManager is tied to PUser.
Is there a better way? Why is PUserManager not inheriting from PManagerBase(Of IPersistentObject)?
This is a problem with generics, if you are using VS 2010 you may want to take a look at covariance and contravariance and modify your IPManagerBase definition accordingly.