WCF can't get object from other project in the same solution - wcf

I have two projects in a solution:
Project A have defined some classes.
Project B is a WCF project and return object from project A
In project A, I write a function to get a list of objects (Song)
public class SongRepository
{
private dbContext db = new dbContext();
public List<Song> getAll()
{
List<Song> songs = db.Songs.ToList();
return songs;
}
}
An in project B, I write a function that used SongRepository to get a list of objects (Song)
public class Service1 : IService1
{
private SongRepository sr = new SongRepository();
public List<Song> getAllSong()
{
List<Song> songs = sr.getAll();
return songs;
}
}
and IService1 class:
namespace webservice
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
List<Song> getAllSong();
}
}
The result is that the WCF project does not return a list of Songs. But I've tested separately in project A and it returns the true data (a list of Songs)
I don't know how to use WCF to get data from another project in the same solution. Can anyone help me?

My problem have solved! Thank you devdigital for answering me.
The solution is that I use an adapter to convert business object to data transfer object. Other people have the same issue as me can go to this link: http://valueinjecter.codeplex.com/
to download the Omu.ValueInjecter dll.
After adding this dll file above, use this two functions to convert BO to DTO:
public T ConvertObjType<T>(object obj)
{
T instance = Activator.CreateInstance<T>();
if (obj != null)
StaticValueInjecter.InjectFrom((object)instance, new object[1]
{
obj
});
return instance;
}
public List<T> ConvertListObjType<G, T>(List<G> listObj)
{
if (listObj == null || listObj.Count == 0)
return (List<T>)null;
List<T> list = new List<T>();
typeof(T).GetProperties();
listObj[0].GetType().GetProperties();
foreach (G g in listObj)
{
object obj = (object)g;
T instance = Activator.CreateInstance<T>();
StaticValueInjecter.InjectFrom((object)instance, new object[1]
{
obj
});
list.Add(instance);
}
return list;
}
I hope this help you out.

Related

MEF Add module twice to catalog

Do you know how to add the same module twice to a catalog with different parameters?
ITest acc1 = new smalltest("a", 0)
ITest acc2 = new smalltest("b", 1)
AggregateCatalog.Catalogs.Add(??)
AggregateCatalog.Catalogs.Add(??)
Thanks in advance!
As MEF is limited to its usage of attributes and can be configured by using the Import and Export attributes unlike the flexibility usually provided by IoC Containers, just how one may extend a Part in MEF, one may extend it from a referenced DLL, you could also do something similar where a class inherits from a previous MEF Part by creating a class which exposes some properties with the [ExportAttribute]. The attribute is not limited to the usage on a class, but can be applied to properties. For example, how about something like this.
public class PartsToExport
{
[Export(typeof(ITest))]
public Implementation A
{
get { return new Implementation("A", 5); }
}
[Export(typeof(ITest))]
public Implementation B
{
get { return new Implementation("B", 10); }
}
}
public interface ITest
{
void WhoAmI(Action<string, int> action);
}
[Export]
public class Implementation : ITest
{
private string _method;
private readonly int _value;
public Implementation(string method, int value)
{
_method = method;
_value = value;
}
public void WhoAmI(Action<string, int> action)
{
action(_method, _value);
}
}
[TestClass]
public class Tests
{
[TestMethod]
public void Test()
{
var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
CompositionContainer container = new CompositionContainer(catalog);
var tests = container.GetExportedValues<ITest>();
foreach (var test in tests)
{
test.WhoAmI((s, i) => Console.WriteLine("I am {0} with a value of {1}.", s, i));
}
}
}
This outputs the following to the console:
I am A with a value of 5.
I am B with a value of 10.

How can I add datacontract to a type (xxxDataTable) which is created by a typed data set?

I have a typed data set and I want to pass tables(which are created by .net) or collection of rows instead of objects(which I would be creating) or collecion of objects to the client side. Silverlight framework doesn't support system.data.datatable.
you don't need to add datacontract attribute to types you don't own. You can implement IDataContractSurrogate to replace instances of client-unknown types with known-type instances (for example lightweight datatable POCO).
If you used code-first approach, you wouldn't have this extra projection-copy operation between typed dataset class objects and your own POCO objects on serialization/deserialization (and you would have full control over data object types (POCOs)).
I find useful to use Json.Net 'any object to JObject' convertor (pretty fast and customizable) as first step before converting to something else:
public static class JsonExtensions
{
public static object Normalize(this JToken token)
{
var type = token.GetType();
if (type == typeof(JObject))
{
return (token as JObject).OfType<JProperty>().ToDictionary<JProperty, string, object>(property => property.Name, property => property.Value.Normalize());
}
if (type == typeof(JProperty))
{
var property = token as JProperty;
//return new DictionaryEntry(property.Name, property.Value.Normalize());
return new KeyValuePair<string, object>(property.Name, property.Value.Normalize());
}
if (type == typeof(JValue))
{
return (token as JValue).Value;
}
if (type == typeof(JArray))
{
//return (token as JArray).OfType<JValue>().Select(value => value.Normalize()).ToArray();
return (token as JArray).Select(value => value.Normalize()).ToArray();
}
throw new NotImplementedException();
//return null;
}
}
public class TestClass
{
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public TestClass RefProperty { get; set; }
}
private static string DataContractXmlSerialize<T>(T source)
{
var serializer = new DataContractSerializer(source.GetType());
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, source);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
Usage:
var test = new TestClass()
{
StringProperty = "StringProperty",
IntProperty = int.MaxValue,
RefProperty = new TestClass() { IntProperty = int.MinValue }
};
var jObj = JObject.FromObject(test);
var dict = jObj.Normalize();
var serializedDict = DataContractXmlSerialize(dict);
as you can see - output is WCF-serializable (standard dictionary being serialized produces not very nice xml with but you can use your own serializable dictionary)
You simply cannot use the ADO.NET implementation of a DataTable in your Silverlight client, but there are alternatives.
However, this blog post has an alternative DataTable implementation that you can serialize and can support in Silverlight.
If you want to access data in Silverlight application you should use RIA Services. You should create custom DTO object and create list of DTO objects from your DataTable rows and return it from RIA Service.
You get started with RIA Services follow MSDN at http://msdn.microsoft.com/en-us/library/ee707376(v=vs.91).aspx

DI in Service Contract WCF

Please find below my code. Employee class implements IEmployee interface.
namespace MiddleWare.ServiceContracts
{
[ServiceContract(Namespace = "http://mywebsite.com/MyProject")]
public interface IMiscellaneous
{
[OperationContract]
[ServiceKnownType(typeof(MiddleWare.Classes.Employee))]
IEnumerable<IEmployee> Search_Employee
(string SearchText);
}
namespace MiddleWare.ServiceClasses
{
public class Miscellaneous : IMiscellaneous
{
public IEnumerable<IEmployee> Search_Employee
(string SearchText)
{
List<IEmployee> emp = new List<IEmployee>();
IEmployee TempObject = (IEmployee)Activator.CreateInstance(typeof(IEmployee));
TempObject.EmployeeId = "12345678";
emp.Add(TempObject);
return emp;
}
}
}
As is visible the above code does compile but wont work because interface instance cannot be created.How can I achive DI(Dependency Injection) here...If I write..
IEmployee TempObject = (IEmployee)Activator.CreateInstance(typeof(Employee));
Then this class will be dependent not only on the Interface but also the class...assuming that one fine day Employee class becomes Employee2.There will be code changes at two places..
1)[ServiceKnownType(typeof(MiddleWare.Classes.Employee2))]
2)IEmployee TempObject = (IEmployee)Activator.CreateInstance(typeof(Employee2));
I want to avoid that. Can we do something at implementation of IOperationBehavior or is there a Ninject way of achieving this or am I trying to achieve impossible?
Consider a design change - Use the factory pattern to create an instance of your employee.
public EmployeeFactory : IEmployeeFactory
{
public IEmployee CreateEmployee()
{
return new Employee();
}
}
And introduce a dependency on the Factory from your middleware, so creating a new IEmployee becomes:
public class Miscellaneous : IMiscellaneous
{
private readonly IEmployeeFasctory _employeeFactory;
public class Miscellaneous(IEmployeeFactory employeeFactory)
{
_employeeFactory = employeeFactory;
}
public IEnumerable Search_Employee (string searchText)
{
List employees = new List();
IEmployee employee = _employeeFactory.CreateEmployee();
employee.EmployeeId = "12345678";
employees.Add(TempObject);
return employees;
}
And then you can inject your EmployeeFactory into Miscellaneous. And should Employee one day become deprecated and Employee2 comes along, just change the factory!
As rich.okelly points out in another answer, IEmployeeFactory should be used to create instances of the IEmployee interface, since IEmployee isn't a Service, but an Entity.
The IEmployeeFactory interface, on the other hand, is a Service, so should be injected into the service class using Constructor Injection. Here's a write-up of enabling Constructor Injection in WCF.
Had a discussion within the team.
1) Constructor based implementation is not comfortable..The service would be IIS hosted and consumed as a web-reference.Cannot ask client systems to provide FactoryImplementatedObjects in Miscellaneous class call.
2) Entity based factories is also not absolutely accurate.If I happen to have say 20 specific entities in my project like Employee,Material,Project,Location,Order then I need to have 20 Factories.Also the Miscellaneous class will have several custom constructors to support specific contract calls..
I have prepared a system which is working and DI is achieved to a great level but I feel like I am cheating OOPS..Doesnt feel correct at heart..but cannot be refuted to be wrong..Please check and let me know your comments.
I now have a IEntity Interface which is the base for all other Entities.
namespace BusinessModel.Interfaces
{
public interface IEntity
{
string EntityDescription { get; set; }
}
}
Hence forth all will implement this.
namespace BusinessModel.Interfaces
{
public interface IEmployee : IEntity
{
string EmployeeId { get; set ; }
}
}
namespace BusinessModel.Interfaces
{
public interface IProject : IEntity
{
string ProjectId { get; set; }
}
}
and so on..(Interface implementing interface..absolutely ridiculous,cheating but working)
Next,An Enum type is declared to have a list of all Entities...
namespace MiddleWare.Common
{
internal enum BusinessModel
{
IEmployee,
IProject
}
}
A DI Helper class is created which will henceforth be considered a part of Business Model and any changes to it (Implementation,Naming..) would be taken as a Business Shift.So if DIHelper class has to become DIHelper2 then this is like BIG.(Can this also be avoided??)
namespace MiddleWare.Common
{
internal sealed class DIHelper
{
internal static IEntity GetRequiredIEntityBasedObject(BusinessModel BusinessModelObject)
{
switch (BusinessModelObject)
{
case BusinessModel.IEmployee:
return new Employee();
}
return null;
}
}
}
Function is Self Explanatory...
So now finally,the contract and implementation...
namespace MiddleWare.ServiceContracts
{
[ServiceContract(Namespace = "http://mywebsite.com/MyProject")]
public interface IMiscellaneous
{
[OperationContract]
[ServiceKnownType(typeof(MiddleWare.Classes.Employee))]
IEnumerable<IEmployee> Search_Employee
(string SearchText);
}
}
namespace MiddleWare.ServiceClasses
{
public class Miscellaneous : IMiscellaneous
{
public IEnumerable<IEmployee> Search_Employee
(string SearchText)
{
List<IEmployee> IEmployeeList = new List<IEmployee>();
IEmployee TempObject = (IEmployee)DIHelper.GetRequiredIEntityBasedObject(MiddleWare.Common.BusinessModel.IEmployee);
TempObject.EmployeeId = "12345678";
IEmployeeList.Add(TempObject);
return IEmployeeList;
}
}
}
What do you say??
My Team is happy though :)
From your updated requirements, there is nothing related to DI in this question...
So, to create a type based on the service known types of a service contract you can use:
public class EntityLoader<TServiceContract>
{
private static readonly HashSet<Type> ServiceKnownTypes = new HashSet<Type>();
static EntityLoader()
{
var attributes = typeof(TServiceContract).GetMethods().SelectMany(m => m.GetCustomAttributes(typeof(ServiceKnownTypeAttribute), true)).Cast<ServiceKnownTypeAttribute>();
foreach (var attribute in attributes)
{
ServiceKnownTypes.Add(attribute.Type);
}
}
public TEntity CreateEntity<TEntity>()
{
var runtimeType = ServiceKnownTypes.Single(t => typeof(TEntity).IsAssignableFrom(t));
return (TEntity)Activator.CreateInstance(runtimeType);
}
}
Which is then useable like so:
[ServiceContract(Namespace = "http://mywebsite.com/MyProject")]
public interface IMiscellaneous
{
[OperationContract]
[ServiceKnownType(typeof(Employee))]
IEnumerable<IEmployee> SearchEmployee(string SearchText);
}
public class Miscellaneous : IMiscellaneous
{
private readonly EntityLoader<IMiscellaneous> _entityLoader = new EntityLoader<IMiscellaneous>();
public IEnumerable<IEmployee> SearchEmployee(string SearchText)
{
List<IEmployee> employees = new List<IEmployee>();
IEmployee employee = _entityLoader.CreateEntity<IEmployee>();
employee.EmployeeId = "12345678";
employees.Add(employee);
return employees;
}
}
Obviously, the above code assumes that ALL of your service entities will contain public parameterless constructors and that there will only be one ServiceKnownType that implements each interface.

Ninject Cascading Inection with IList

I am trying to use Ninject to implement cascading injection into a class that contains an IList field. It seems that, unless I specifically specify each binding to use in the kernel.Get method, the IList property is always injected with a list of a single default object.
The following VSTest code illustrates the problem. The first test fails because the IList field contains one MyType object with Name=null. The second test passes, but I had to specifically tell Ninject what constructor arguments to use. I am using the latest build from the ninject.web.mvc project for MVC 3.
Does Ninject specifically treat IList different, or is there a better way to handle this? Note that this seems to only be a problem when using an IList. Createing a custom collection object that wraps IList works as expected in the first test.
[TestClass()]
public class NinjectTest
{
[TestMethod()]
public void ListTest_Fails_NameNullAndCountIncorrect()
{
var kernel = new Ninject.StandardKernel(new MyNinjectModule());
var target = kernel.Get<MyModel>();
var actual = target.GetList();
// Fails. Returned value is set to a list of a single object equal to default(MyType)
Assert.AreEqual(2, actual.Count());
// Fails because MyType object is initialized with a null "Name" property
Assert.AreEqual("Fred", actual.First().Name);
}
[TestMethod()]
public void ListTest_Passes_SeemsLikeUnnecessaryConfiguration()
{
var kernel = new Ninject.StandardKernel(new MyNinjectModule());
var target = kernel.Get<MyModel>(new ConstructorArgument("myGenericObject", kernel.Get<IGenericObject<MyType>>(new ConstructorArgument("myList", kernel.Get<IList<MyType>>()))));
var actual = target.GetList();
Assert.AreEqual(2, actual.Count());
Assert.AreEqual("Fred", actual.First().Name);
}
}
public class MyNinjectModule : NinjectModule
{
public override void Load()
{
Bind<IList<MyType>>().ToConstant(new List<MyType> { new MyType { Name = "Fred" }, new MyType { Name = "Bob" } });
Bind<IGenericObject<MyType>>().To<StubObject<MyType>>();
}
}
public class MyModel
{
private IGenericObject<MyType> myGenericObject;
public MyModel(IGenericObject<MyType> myGenericObject)
{
this.myGenericObject = myGenericObject;
}
public IEnumerable<MyType> GetList()
{
return myGenericObject.GetList();
}
}
public interface IGenericObject<T>
{
IList<T> GetList();
}
public class StubObject<T> : IGenericObject<T>
{
private IList<T> _myList;
public StubObject(IList<T> myList)
{
_myList = myList;
}
public IList<T> GetList()
{
return _myList;
}
}
public class MyType
{
public String Name { get; set; }
}
lists, collections and arrays are handled slightly different. For those types ninject will inject a list or array containing an instance of all bindings for the generic type. In your case the implementation type is a class which is aoutobound by default. So the list will contain one instance of that class. If you add an interface to that class and use this one the list will be empty.

Ninject 2.0 - What's the alternative to ConventionMemberSelector

I have just downloaded the latest version of Ninject and replaced our existing Ninject.Core and Ninject.Condidtions assemblies with the single Ninject.dll (CF builds if that makes a difference). All has gone smoothly until I get to:
kernel.Components.Connect<IMemberSelector>(new MyMemberSelector());
Which is implemented:
public class MyMemberSelector : ConventionMemberSelector
{
protected override void DeclareHeuristics()
{
InjectProperties(When.Property.Name.StartsWith("View"));
}
}
I can't find any reference to what this has been replaced with and my bindings don't just work - the View properties aren't injected.
Can anyone help?
Thanks
You can implement your own IInjectionHeuristic and add it as a Kernel component.
var selector = kernel.Components.Get<ISelector>();
var heuristic = new PropertyMemberSelector(member => member.Name.StartsWith("View"));
selector.InjectionHeuristics.Add(heuristic);
public class PropertyMemberSelector
: NinjectComponent, IInjectionHeuristic
{
private readonly Func<MemberInfo, bool> _predicate;
public PropertyMemberSelector(Func<MemberInfo, bool> predicate)
{
_predicate = predicate;
}
public bool ShouldInject(MemberInfo member)
{
return member.MemberType == MemberTypes.Property && _predicate( member );
}
}
Regards,
Ian