Search Results

Search found 122 results on 5 pages for 'irepository'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • What's the correct way to instantiate an IRepository class from the Controller?

    - by GenericTypeTea
    I have the following project layout: MVC UI |...CustomerController (ICustomerRepository - how do I instantiate this?) Data Model |...ICustomerRepository DAL (Separate Data access layer, references Data Model to get the IxRepositories) |...CustomerRepository (inherits ICustomerRepository) What's the correct way to say ICustomerRepository repository = new CustomerRepository(); when the Controller has no visibility to the DAL project? Or am I doing this completely wrong?

    Read the article

  • SubSonic LInq IRepository

    - by ajwaka
    Trying to use SubSonic 3.0.0.4's Linq TEmplates. Got everything working. But in the Doc's I'm seeing how I can use aa IRepository to bulk insert, update, delete my db. Thing is - It wasn't included in the download. Is it somewhere else and I simply overlooked it? I've got a ton of updates going from one "Save" call - so this would be very helpful! Thanks

    Read the article

  • IRepository with Inherited Classes

    - by Stacey
    In keeping with the Repository pattern of data input, I've a question in regards to using inherited classes. For instance, suppose I would have the class... class Employee IEmployeeRepository { Add(Employee employee); } This works fine, nothing wrong with it so far... but now let's say I continue on.. class Manager : Employee Okay, now let's assume that I never need to enter a manager different than an Employee? What's the best approach here? Would a scenario such as .. IEmployeeRepository { Add<T>(T employee) where T : Employee } Be the best approach, or do I need to abstract a different repository for each type?

    Read the article

  • Inheriting and overriding interfaces in C#

    - by Daniel A. White
    Please note: I am writing this question. I have these interfaces in a library/framework I am working on: interface IRepository<TKey,TModel> { void Remove(TModel entity); } interface IRepository<T> : IRepository<int, T> { } interface ISoftDeleteRepository<TKey,TModel> : IRepository<TKey, TModel> { } interface ISoftDeleteRepository<TModel> : ISoftDeleteRepository<int, TModel>, IRepository<TModel> { } and these implementations class Repository : IRepository { void Remove(TModel entity) { // actually Delete } } interface IRepository<T> : IRepository<int, T> { } interface ISoftDeleteRepository<TKey,TModel> : IRepository<TKey, TModel> { } interface ISoftDeleteRepository<TModel> : ISoftDeleteRepository<int, TModel>, IRepository<TModel> { }

    Read the article

  • Inject same DataContext instance across several types with Unity

    - by Sergejus
    Suppose I have IRepository interface and its implementation SqlRepository that takes as an argument LINQ to SQL DataContext. Suppose as well that I have IService interface and its implementation Services that takes three IRepository, IRepository and IRepository. Demo code is below: public interface IRepository<T> { } public class SqlRepository<T> : IRepository<T> { public SqlRepository(DataContext dc) { ... } } public interface IService<T> { } public class Service<T,T1,T2,T3> : IService<T> { public Service(IRepository<T1> r1, IRepository<T2>, IRepository<T3>) { ... } } Is it any way while creating Service class to inject all three repositories with the same DataContext?

    Read the article

  • Generic Repositories with DI & Data Intensive Controllers

    - by James
    Usually, I consider a large number of parameters as an alarm bell that there may be a design problem somewhere. I am using a Generic Repository for an ASP.NET application and have a Controller with a growing number of parameters. public class GenericRepository<T> : IRepository<T> where T : class { protected DbContext Context { get; set; } protected DbSet<T> DbSet { get; set; } public GenericRepository(DbContext context) { Context = context; DbSet = context.Set<T>(); } ...//methods excluded to keep the question readable } I am using a DI container to pass in the DbContext to the generic repository. So far, this has met my needs and there are no other concrete implmentations of IRepository<T>. However, I had to create a dashboard which uses data from many Entities. There was also a form containing a couple of dropdown lists. Now using the generic repository this makes the parameter requirments grow quickly. The Controller will end up being something like public HomeController(IRepository<EntityOne> entityOneRepository, IRepository<EntityTwo> entityTwoRepository, IRepository<EntityThree> entityThreeRepository, IRepository<EntityFour> entityFourRepository, ILogError logError, ICurrentUser currentUser) { } It has about 6 IRepositories plus a few others to include the required data and the dropdown list options. In my mind this is too many parameters. From a performance point of view, there is only 1 DBContext per request and the DI container will serve the same DbContext to all of the Repositories. From a code standards/readability point of view it's ugly. Is there a better way to handle this situation? Its a real world project with real world time constraints so I will not dwell on it too long, but from a learning perspective it would be good to see how such situations are handled by others.

    Read the article

  • Configuring Unity with a closed generic constructor parmater

    - by fearofawhackplanet
    I've been trying to read the article here but I still can't understand it. I have a constructor resembling the following: IOrderStore orders = new OrderStore(new Repository<Order>(new OrdersDataContext())); The constructor for OrderStore: public OrderStore(IRepository<Order> orderRepository) Constructor for Repository<T>: public Repository(DataContext dataContext) How do I set this up in the Unity config file? UPDATE: I've spent the last few hours banging my head against this, and although I'm not really any closer to getting it right I think at least I can be a little more specific about the problem. I've got my IRespository<T> working ok: <typeAlias alias="IRepository" type="MyAssembly.IRepository`1, MyAssembly" /> <typeAlias alias="Repository" type="MyAssembly.Repository`1, MyAssembly" /> <typeAlias alias="OrdersDataContext" type="MyAssembly.OrdersDataContext, MyAssembly" /> <types> <type type="OrdersDataContext"> <typeConfig> <constructor /> <!-- ensures paramaterless constructor used --> </typeConfig> </type> <type type="IRepository" mapTo="Repository"> <typeConfig> <constructor> <param name="dataContext" parameterType="OrdersDataContext"> <dependency /> </param> </constructor> </typeConfig> </type> </types> So now I can get an IRepository like so: IRepository rep = _container.Resolve(); and that all works fine. The problem now is when trying to add the configuration for IOrderStore <type type="IOrderStore" mapTo="OrderStore"> <typeConfig> <constructor> <param name="ordersRepository" parameterType="IRepository"> <dependency /> </param> </constructor> </typeConfig> </type> When I add this, Unity blows up when trying to load the config file. The error message is OrderStore does not have a constructor that takes the parameters (IRepository`1). What I think this is complaining about is because the OrderStore constructor takes a closed IRepository generic type, ie OrderStore(IRepository<Order>) and not OrderStore(IRepository<T>) I don't have any idea how to resolve this.

    Read the article

  • Constructor Injection and when to use a Service Locator

    - by Simon
    I'm struggling to understand parts of StructureMap's usage. In particular, in the documentation a statement is made regarding a common anti-pattern, the use of StructureMap as a Service Locator only instead of constructor injection (code samples straight from Structuremap documentation): public ShippingScreenPresenter() { _service = ObjectFactory.GetInstance<IShippingService>(); _repository = ObjectFactory.GetInstance<IRepository>(); } instead of: public ShippingScreenPresenter(IShippingService service, IRepository repository) { _service = service; _repository = repository; } This is fine for a very short object graph, but when dealing with objects many levels deep, does this imply that you should pass down all the dependencies required by the deeper objects right from the top? Surely this breaks encapsulation and exposes too much information about the implementation of deeper objects. Let's say I'm using the Active Record pattern, so my record needs access to a data repository to be able to save and load itself. If this record is loaded inside an object, does that object call ObjectFactory.CreateInstance() and pass it into the active record's constructor? What if that object is inside another object. Does it take the IRepository in as its own parameter from further up? That would expose to the parent object the fact that we're access the data repository at this point, something the outer object probably shouldn't know. public class OuterClass { public OuterClass(IRepository repository) { // Why should I know that ThingThatNeedsRecord needs a repository? // that smells like exposed implementation to me, especially since // ThingThatNeedsRecord doesn't use the repo itself, but passes it // to the record. // Also where do I create repository? Have to instantiate it somewhere // up the chain of objects ThingThatNeedsRecord thing = new ThingThatNeedsRecord(repository); thing.GetAnswer("question"); } } public class ThingThatNeedsRecord { public ThingThatNeedsRecord(IRepository repository) { this.repository = repository; } public string GetAnswer(string someParam) { // create activeRecord(s) and process, returning some result // part of which contains: ActiveRecord record = new ActiveRecord(repository, key); } private IRepository repository; } public class ActiveRecord { public ActiveRecord(IRepository repository) { this.repository = repository; } public ActiveRecord(IRepository repository, int primaryKey); { this.repositry = repository; Load(primaryKey); } public void Save(); private void Load(int primaryKey) { this.primaryKey = primaryKey; // access the database via the repository and set someData } private IRepository repository; private int primaryKey; private string someData; } Any thoughts would be appreciated. Simon

    Read the article

  • StructureMap: Wiring (generic) implementations to an implementation of another type

    - by Jeremy Frey
    If I have an interface: public interface IRepository<T> And an abstract class: public abstract class LinqToSqlRepository<T, TContext> : IRepository<T> where T : class where TContext : DataContext And a whole bunch of implementations of IRepository / LinqToSqlRepository (e.g. AccountRepository, ContactRepository, etc.), what's the best way to to use StructureMap (2.5.3) to generically wire them all up? e.g., I want this code to pass: [Test] public void ShouldWireUpAccountRepositories { var accountRepo = ObjectFactory.GetInstance<IRepository<Account>>(); Assert.IsInstanceOf<AccountRepository>(accountRepo); } Without explicitly writing this: ObjectFactory.Configure(x => x.ForRequestedType<IRepository<Account>>() .TheDefaultIsConcreteType<AccountRepository>()); In the past, we've always created a specific interface on each repository that inherited from the generic one, and used the default scanner to automatically wire all of those instances, but I'd like to be able to ask specifically for an IRepository<Account> without cluttering up the project with additional interfaces / configurations.

    Read the article

  • IXRepository and test problems

    - by Ridermansb
    Recently had a doubt about how and where to test repository methods. Let the following situation: I have an interface IRepository like this: public interface IRepository<T> where T: class, IEntity { IQueryable<T> Query(Expression<Func<T, bool>> expression); // ... Omitted } And a generic implementation of IRepository public class Repository<T> : IRepository<T> where T : class, IEntity { public IQueryable<T> Query(Expression<Func<T, bool>> expression) { return All().Where(expression).AsQueryable(); } } This is an implementation base that can be used by any repository. It contains the basic implementation of my ORM. Some repositories have specific filters, in which case we will IEmployeeRepository with a specific filter: public interface IEmployeeRepository : IRepository<Employee> { IQueryable<Employee> GetInactiveEmployees(); } And the implementation of IEmployeeRepository: public class EmployeeRepository : Repository<Employee>, IEmployeeRepository // TODO: I have a dependency with ORM at this point in Repository<Employee>. How to solve? How to test the GetInactiveEmployees method { public IQueryable<Employee> GetInactiveEmployees() { return Query(p => p.Status != StatusEmployeeEnum.Active || p.StartDate < DateTime.Now); } } Questions Is right to inherit Repository<Employee>? The goal is to reuse code once all implementing IRepository already been made. If EmployeeRepository inherit only IEmployeeRepository, I have to literally copy and paste the code of Repository<T>. In our example, in EmployeeRepository : Repository<Employee> our Repository lies in our ORM layer. We have a dependency here with our ORM impossible to perform some unit test. How to create a unit test to ensure that the filter GetInactiveEmployees return all Employees in which the Status != Active and StartDate < DateTime.Now. I can not create a Fake/Mock of IEmployeeRepository because I would be testing? Need to test the actual implementation of GetInactiveEmployees. The complete code can be found on Github

    Read the article

  • Static DataService class vs. IRepository<T> ?

    - by msfanboy
    Hello, I am just studying the code of Sacha Barbers MVVM framework Chinch and I saw this in the xxxViewModel.cs file: DataService.FetchAllOrders(CurrentCustomer.CustomerId.DataValue); DataService is a Static class. Being a junior dev I am only used to Interfaces with Data services. Why is that class static? Or do you think he made it just for the example? So is that a good approach?

    Read the article

  • How to use InterfaceInterceptor with NServiceBus UnityBuilder

    - by David
    I have a MessageHandler with a dependency declared as: public IRepository<Person> PersonRepository {get;set;} I set up my Unity container with: IUnityContainer container = new UnityContainer(); container.AddNewExtension<Interception>(); container.RegisterType(typeof(IRepository<Person>), typeof(Example.Data.InMemory.Repository<Person>)); container.Configure<Interception>() .AddPolicy("PersonAddAdvice") .AddMatchingRule(new AddMatchingRule()) .AddCallHandler(new PersonAddedEventPublishingCallHandler()); container.Configure<Interception>() .SetInterceptorFor<IRepository<Person>>(new InterfaceInterceptor()); Then I Init my endpoint with: class EndpointConfig : IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization { public void Init() { NServiceBus.Configure.With() .Log4Net() .UnityBuilder(ContainerConfig.LoadContainer()) .XmlSerializer(); } } (ContainerConfig.LoadContainer() returns the pre-configured IUnityContainer) the problem is that the IRepository dependency in my MessageHandler is not resolved (it's null when handling the messages). If I remove the interception configuration from the Unity container, and simply do this: IUnityContainer container = new UnityContainer(); container.RegisterType(typeof(IRepository<Person>), typeof(Example.Data.InMemory.Repository<Person>)); It works as expected, and the MessageHandler has an instance if IRepository resolved.

    Read the article

  • How can I inject multiple repositories in a NServicebus message handler?

    - by Paco
    I use the following: public interface IRepository<T> { void Add(T entity); } public class Repository<T> { private readonly ISession session; public Repository(ISession session) { this.session = session; } public void Add(T entity) { session.Save(entity); } } public class SomeHandler : IHandleMessages<SomeMessage> { private readonly IRepository<EntityA> aRepository; private readonly IRepository<EntityB> bRepository; public SomeHandler(IRepository<EntityA> aRepository, IRepository<EntityB> bRepository) { this.aRepository = aRepository; this.bRepository = bRepository; } public void Handle(SomeMessage message) { aRepository.Add(new A(message.Property); bRepository.Add(new B(message.Property); } } public class MessageEndPoint : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization { public void Init() { ObjectFactory.Configure(config => { config.For<ISession>() .CacheBy(InstanceScope.ThreadLocal) .TheDefault.Is.ConstructedBy(ctx => ctx.GetInstance<ISessionFactory>().OpenSession()); config.ForRequestedType(typeof(IRepository<>)) .TheDefaultIsConcreteType(typeof(Repository<>)); } } My problem with the threadlocal storage is, is that the same session is used during the whole application thread. I discovered this when I saw the first level cache wasn't cleared. What I want is using a new session instance, before each call to IHandleMessages<.Handle. How can I do this with structuremap? Do I have to create a message module?

    Read the article

  • ASP.NET MVC Patterns

    - by Sam Striano
    Hello, I am fairly new to MVC, but after playing with it (MVC 3/Razor), I am hooked. I have a few questions: 1) What is the best, or most widely used pattern to develop MVC apps in? Repository, DDD, UOW? 2) I am using the Entity Framework 4, so could some please explain to me or point me to a good source that will explain the Repository Pattern w/EF4? Doesn't EF4 take place as the business layer and the data access layer? Does the Repository Pattern even provide a benefit? 3) Also, one last question, could someone explain the whole relationship between the Controller, the Model and the View? I get the basics, but maybe a little more in depth of the correct way to use it. View Models - Say I have a view that displays customer info, and one that edits it, should I have a view model and an edit model, or can the be passed around? 4) Examples?? Thanks for the help up front, $("Sam") ** EDIT ** Am I on the right track here: Public Class HomeController Inherits System.Web.Mvc.Controller Function Index(ByVal id As Integer) As ActionResult Return View(New HomeModel) End Function <HttpPost()> _ Function Index(ByVal Model As HomeModel) As ActionResult Return View(Model) End Function End Class Public Class HomeModel Private _Repository As IRepository(Of Customer) Public Property Customer As Customer Public Sub New() End Sub Public Sub New(ByVal ID As Integer) _Repository = New CustomerRepository Customer = _Repository.GetByID(ID) End Sub End Class Public Interface IRepository(Of T) Function GetByID(ByVal ID As Integer) As T Sub Add(ByVal Entity As T) Sub Delete(ByVal Entity As T) End Interface Public Class CustomerRepository Implements IRepository(Of Customer) Public Sub Add(ByVal Entity As Customer) Implements IRepository(Of Customer).Add End Sub Public Sub Delete(ByVal Entity As Customer) Implements IRepository(Of Customer).Delete End Sub Public Function GetByID(ByVal ID As Integer) As Customer Implements IRepository(Of Customer).GetByID Return New Customer With {.ID = ID, .FirstName = "Sam", .LastName = "Striano"} End Function End Class Public Class Customer Public Property ID As Integer Public Property FirstName As String Public Property LastName As String End Class

    Read the article

  • Creating a dynamic proxy generator with c# – Part 3 – Creating the constructors

    - by SeanMcAlinden
    Creating a dynamic proxy generator with c# – Part 1 – Creating the Assembly builder, Module builder and caching mechanism Creating a dynamic proxy generator with c# – Part 2 – Interceptor Design For the latest code go to http://rapidioc.codeplex.com/ When building our proxy type, the first thing we need to do is build the constructors. There needs to be a corresponding constructor for each constructor on the passed in base type. We also want to create a field to store the interceptors and construct this list within each constructor. So assuming the passed in base type is a User<int, IRepository> class, were looking to generate constructor code like the following:   Default Constructor public User`2_RapidDynamicBaseProxy() {     this.interceptors = new List<IInterceptor<User<int, IRepository>>>();     DefaultInterceptor<User<int, IRepository>> item = new DefaultInterceptor<User<int, IRepository>>();     this.interceptors.Add(item); }     Parameterised Constructor public User`2_RapidDynamicBaseProxy(IRepository repository1) : base(repository1) {     this.interceptors = new List<IInterceptor<User<int, IRepository>>>();     DefaultInterceptor<User<int, IRepository>> item = new DefaultInterceptor<User<int, IRepository>>();     this.interceptors.Add(item); }   As you can see, we first populate a field on the class with a new list of the passed in base type. Construct our DefaultInterceptor class. Add the DefaultInterceptor instance to our interceptor collection. Although this seems like a relatively small task, there is a fair amount of work require to get this going. Instead of going through every line of code – please download the latest from http://rapidioc.codeplex.com/ and debug through. In this post I’m going to concentrate on explaining how it works. TypeBuilder The TypeBuilder class is the main class used to create the type. You instantiate a new TypeBuilder using the assembly module we created in part 1. /// <summary> /// Creates a type builder. /// </summary> /// <typeparam name="TBase">The type of the base class to be proxied.</typeparam> public static TypeBuilder CreateTypeBuilder<TBase>() where TBase : class {     TypeBuilder typeBuilder = DynamicModuleCache.Get.DefineType         (             CreateTypeName<TBase>(),             TypeAttributes.Class | TypeAttributes.Public,             typeof(TBase),             new Type[] { typeof(IProxy) }         );       if (typeof(TBase).IsGenericType)     {         GenericsHelper.MakeGenericType(typeof(TBase), typeBuilder);     }       return typeBuilder; }   private static string CreateTypeName<TBase>() where TBase : class {     return string.Format("{0}_RapidDynamicBaseProxy", typeof(TBase).Name); } As you can see, I’ve create a new public class derived from TBase which also implements my IProxy interface, this is used later for adding interceptors. If the base type is generic, the following GenericsHelper.MakeGenericType method is called. GenericsHelper using System; using System.Reflection.Emit; namespace Rapid.DynamicProxy.Types.Helpers {     /// <summary>     /// Helper class for generic types and methods.     /// </summary>     internal static class GenericsHelper     {         /// <summary>         /// Makes the typeBuilder a generic.         /// </summary>         /// <param name="concrete">The concrete.</param>         /// <param name="typeBuilder">The type builder.</param>         public static void MakeGenericType(Type baseType, TypeBuilder typeBuilder)         {             Type[] genericArguments = baseType.GetGenericArguments();               string[] genericArgumentNames = GetArgumentNames(genericArguments);               GenericTypeParameterBuilder[] genericTypeParameterBuilder                 = typeBuilder.DefineGenericParameters(genericArgumentNames);               typeBuilder.MakeGenericType(genericTypeParameterBuilder);         }           /// <summary>         /// Gets the argument names from an array of generic argument types.         /// </summary>         /// <param name="genericArguments">The generic arguments.</param>         public static string[] GetArgumentNames(Type[] genericArguments)         {             string[] genericArgumentNames = new string[genericArguments.Length];               for (int i = 0; i < genericArguments.Length; i++)             {                 genericArgumentNames[i] = genericArguments[i].Name;             }               return genericArgumentNames;         }     } }       As you can see, I’m getting all of the generic argument types and names, creating a GenericTypeParameterBuilder and then using the typeBuilder to make the new type generic. InterceptorsField The interceptors field will store a List<IInterceptor<TBase>>. Fields are simple made using the FieldBuilder class. The following code demonstrates how to create the interceptor field. FieldBuilder interceptorsField = typeBuilder.DefineField(     "interceptors",     typeof(System.Collections.Generic.List<>).MakeGenericType(typeof(IInterceptor<TBase>)),       FieldAttributes.Private     ); The field will now exist with the new Type although it currently has no data – we’ll deal with this in the constructor. Add method for interceptorsField To enable us to add to the interceptorsField list, we are going to utilise the Add method that already exists within the System.Collections.Generic.List class. We still however have to create the methodInfo necessary to call the add method. This can be done similar to the following: Add Interceptor Field MethodInfo addInterceptor = typeof(List<>)     .MakeGenericType(new Type[] { typeof(IInterceptor<>).MakeGenericType(typeof(TBase)) })     .GetMethod     (        "Add",        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,        null,        new Type[] { typeof(IInterceptor<>).MakeGenericType(typeof(TBase)) },        null     ); So we’ve create a List<IInterceptor<TBase>> type, then using the type created a method info called Add which accepts an IInterceptor<TBase>. Now in our constructor we can use this to call this.interceptors.Add(// interceptor); Building the Constructors This will be the first hard-core part of the proxy building process so I’m going to show the class and then try to explain what everything is doing. For a clear view, download the source from http://rapidioc.codeplex.com/, go to the test project and debug through the constructor building section. Anyway, here it is: DynamicConstructorBuilder using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Rapid.DynamicProxy.Interception; using Rapid.DynamicProxy.Types.Helpers; namespace Rapid.DynamicProxy.Types.Constructors {     /// <summary>     /// Class for creating the proxy constructors.     /// </summary>     internal static class DynamicConstructorBuilder     {         /// <summary>         /// Builds the constructors.         /// </summary>         /// <typeparam name="TBase">The base type.</typeparam>         /// <param name="typeBuilder">The type builder.</param>         /// <param name="interceptorsField">The interceptors field.</param>         public static void BuildConstructors<TBase>             (                 TypeBuilder typeBuilder,                 FieldBuilder interceptorsField,                 MethodInfo addInterceptor             )             where TBase : class         {             ConstructorInfo interceptorsFieldConstructor = CreateInterceptorsFieldConstructor<TBase>();               ConstructorInfo defaultInterceptorConstructor = CreateDefaultInterceptorConstructor<TBase>();               ConstructorInfo[] constructors = typeof(TBase).GetConstructors();               foreach (ConstructorInfo constructorInfo in constructors)             {                 CreateConstructor<TBase>                     (                         typeBuilder,                         interceptorsField,                         interceptorsFieldConstructor,                         defaultInterceptorConstructor,                         addInterceptor,                         constructorInfo                     );             }         }           #region Private Methods           private static void CreateConstructor<TBase>             (                 TypeBuilder typeBuilder,                 FieldBuilder interceptorsField,                 ConstructorInfo interceptorsFieldConstructor,                 ConstructorInfo defaultInterceptorConstructor,                 MethodInfo AddDefaultInterceptor,                 ConstructorInfo constructorInfo             ) where TBase : class         {             Type[] parameterTypes = GetParameterTypes(constructorInfo);               ConstructorBuilder constructorBuilder = CreateConstructorBuilder(typeBuilder, parameterTypes);               ILGenerator cIL = constructorBuilder.GetILGenerator();               LocalBuilder defaultInterceptorMethodVariable =                 cIL.DeclareLocal(typeof(DefaultInterceptor<>).MakeGenericType(typeof(TBase)));               ConstructInterceptorsField(interceptorsField, interceptorsFieldConstructor, cIL);               ConstructDefaultInterceptor(defaultInterceptorConstructor, cIL, defaultInterceptorMethodVariable);               AddDefaultInterceptorToInterceptorsList                 (                     interceptorsField,                     AddDefaultInterceptor,                     cIL,                     defaultInterceptorMethodVariable                 );               CreateConstructor(constructorInfo, parameterTypes, cIL);         }           private static void CreateConstructor(ConstructorInfo constructorInfo, Type[] parameterTypes, ILGenerator cIL)         {             cIL.Emit(OpCodes.Ldarg_0);               if (parameterTypes.Length > 0)             {                 LoadParameterTypes(parameterTypes, cIL);             }               cIL.Emit(OpCodes.Call, constructorInfo);             cIL.Emit(OpCodes.Ret);         }           private static void LoadParameterTypes(Type[] parameterTypes, ILGenerator cIL)         {             for (int i = 1; i <= parameterTypes.Length; i++)             {                 cIL.Emit(OpCodes.Ldarg_S, i);             }         }           private static void AddDefaultInterceptorToInterceptorsList             (                 FieldBuilder interceptorsField,                 MethodInfo AddDefaultInterceptor,                 ILGenerator cIL,                 LocalBuilder defaultInterceptorMethodVariable             )         {             cIL.Emit(OpCodes.Ldarg_0);             cIL.Emit(OpCodes.Ldfld, interceptorsField);             cIL.Emit(OpCodes.Ldloc, defaultInterceptorMethodVariable);             cIL.Emit(OpCodes.Callvirt, AddDefaultInterceptor);         }           private static void ConstructDefaultInterceptor             (                 ConstructorInfo defaultInterceptorConstructor,                 ILGenerator cIL,                 LocalBuilder defaultInterceptorMethodVariable             )         {             cIL.Emit(OpCodes.Newobj, defaultInterceptorConstructor);             cIL.Emit(OpCodes.Stloc, defaultInterceptorMethodVariable);         }           private static void ConstructInterceptorsField             (                 FieldBuilder interceptorsField,                 ConstructorInfo interceptorsFieldConstructor,                 ILGenerator cIL             )         {             cIL.Emit(OpCodes.Ldarg_0);             cIL.Emit(OpCodes.Newobj, interceptorsFieldConstructor);             cIL.Emit(OpCodes.Stfld, interceptorsField);         }           private static ConstructorBuilder CreateConstructorBuilder(TypeBuilder typeBuilder, Type[] parameterTypes)         {             return typeBuilder.DefineConstructor                 (                     MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName                     | MethodAttributes.HideBySig, CallingConventions.Standard, parameterTypes                 );         }           private static Type[] GetParameterTypes(ConstructorInfo constructorInfo)         {             ParameterInfo[] parameterInfoArray = constructorInfo.GetParameters();               Type[] parameterTypes = new Type[parameterInfoArray.Length];               for (int p = 0; p < parameterInfoArray.Length; p++)             {                 parameterTypes[p] = parameterInfoArray[p].ParameterType;             }               return parameterTypes;         }           private static ConstructorInfo CreateInterceptorsFieldConstructor<TBase>() where TBase : class         {             return ConstructorHelper.CreateGenericConstructorInfo                 (                     typeof(List<>),                     new Type[] { typeof(IInterceptor<TBase>) },                     BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic                 );         }           private static ConstructorInfo CreateDefaultInterceptorConstructor<TBase>() where TBase : class         {             return ConstructorHelper.CreateGenericConstructorInfo                 (                     typeof(DefaultInterceptor<>),                     new Type[] { typeof(TBase) },                     BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic                 );         }           #endregion     } } So, the first two tasks within the class should be fairly clear, we are creating a ConstructorInfo for the interceptorField list and a ConstructorInfo for the DefaultConstructor, this is for instantiating them in each contructor. We then using Reflection get an array of all of the constructors in the base class, we then loop through the array and create a corresponding proxy contructor. Hopefully, the code is fairly easy to follow other than some new types and the dreaded Opcodes. ConstructorBuilder This class defines a new constructor on the type. ILGenerator The ILGenerator allows the use of Reflection.Emit to create the method body. LocalBuilder The local builder allows the storage of data in local variables within a method, in this case it’s the constructed DefaultInterceptor. Constructing the interceptors field The first bit of IL you’ll come across as you follow through the code is the following private method used for constructing the field list of interceptors. private static void ConstructInterceptorsField             (                 FieldBuilder interceptorsField,                 ConstructorInfo interceptorsFieldConstructor,                 ILGenerator cIL             )         {             cIL.Emit(OpCodes.Ldarg_0);             cIL.Emit(OpCodes.Newobj, interceptorsFieldConstructor);             cIL.Emit(OpCodes.Stfld, interceptorsField);         } The first thing to know about generating code using IL is that you are using a stack, if you want to use something, you need to push it up the stack etc. etc. OpCodes.ldArg_0 This opcode is a really interesting one, basically each method has a hidden first argument of the containing class instance (apart from static classes), constructors are no different. This is the reason you can use syntax like this.myField. So back to the method, as we want to instantiate the List in the interceptorsField, first we need to load the class instance onto the stack, we then load the new object (new List<TBase>) and finally we store it in the interceptorsField. Hopefully, that should follow easily enough in the method. In each constructor you would now have this.interceptors = new List<User<int, IRepository>>(); Constructing and storing the DefaultInterceptor The next bit of code we need to create is the constructed DefaultInterceptor. Firstly, we create a local builder to store the constructed type. Create a local builder LocalBuilder defaultInterceptorMethodVariable =     cIL.DeclareLocal(typeof(DefaultInterceptor<>).MakeGenericType(typeof(TBase))); Once our local builder is ready, we then need to construct the DefaultInterceptor<TBase> and store it in the variable. Connstruct DefaultInterceptor private static void ConstructDefaultInterceptor     (         ConstructorInfo defaultInterceptorConstructor,         ILGenerator cIL,         LocalBuilder defaultInterceptorMethodVariable     ) {     cIL.Emit(OpCodes.Newobj, defaultInterceptorConstructor);     cIL.Emit(OpCodes.Stloc, defaultInterceptorMethodVariable); } As you can see, using the ConstructorInfo named defaultInterceptorConstructor, we load the new object onto the stack. Then using the store local opcode (OpCodes.Stloc), we store the new object in the local builder named defaultInterceptorMethodVariable. Add the constructed DefaultInterceptor to the interceptors field collection Using the add method created earlier in this post, we are going to add the new DefaultInterceptor object to the interceptors field collection. Add Default Interceptor private static void AddDefaultInterceptorToInterceptorsList     (         FieldBuilder interceptorsField,         MethodInfo AddDefaultInterceptor,         ILGenerator cIL,         LocalBuilder defaultInterceptorMethodVariable     ) {     cIL.Emit(OpCodes.Ldarg_0);     cIL.Emit(OpCodes.Ldfld, interceptorsField);     cIL.Emit(OpCodes.Ldloc, defaultInterceptorMethodVariable);     cIL.Emit(OpCodes.Callvirt, AddDefaultInterceptor); } So, here’s whats going on. The class instance is first loaded onto the stack using the load argument at index 0 opcode (OpCodes.Ldarg_0) (remember the first arg is the hidden class instance). The interceptorsField is then loaded onto the stack using the load field opcode (OpCodes.Ldfld). We then load the DefaultInterceptor object we stored locally using the load local opcode (OpCodes.Ldloc). Then finally we call the AddDefaultInterceptor method using the call virtual opcode (Opcodes.Callvirt). Completing the constructor The last thing we need to do is complete the constructor. Complete the constructor private static void CreateConstructor(ConstructorInfo constructorInfo, Type[] parameterTypes, ILGenerator cIL)         {             cIL.Emit(OpCodes.Ldarg_0);               if (parameterTypes.Length > 0)             {                 LoadParameterTypes(parameterTypes, cIL);             }               cIL.Emit(OpCodes.Call, constructorInfo);             cIL.Emit(OpCodes.Ret);         }           private static void LoadParameterTypes(Type[] parameterTypes, ILGenerator cIL)         {             for (int i = 1; i <= parameterTypes.Length; i++)             {                 cIL.Emit(OpCodes.Ldarg_S, i);             }         } So, the first thing we do again is load the class instance using the load argument at index 0 opcode (OpCodes.Ldarg_0). We then load each parameter using OpCode.Ldarg_S, this opcode allows us to specify an index position for each argument. We then setup calling the base constructor using OpCodes.Call and the base constructors ConstructorInfo. Finally, all methods are required to return, even when they have a void return. As there are no values on the stack after the OpCodes.Call line, we can safely call the OpCode.Ret to give the constructor a void return. If there was a value, we would have to pop the value of the stack before calling return otherwise, the method would try and return a value. Conclusion This was a slightly hardcore post but hopefully it hasn’t been too hard to follow. The main thing is that a number of the really useful opcodes have been used and now the dynamic proxy is capable of being constructed. If you download the code and debug through the tests at http://rapidioc.codeplex.com/, you’ll be able to create proxies at this point, they cannon do anything in terms of interception but you can happily run the tests, call base methods and properties and also take a look at the created assembly in Reflector. Hope this is useful. The next post should be up soon, it will be covering creating the private methods for calling the base class methods and properties. Kind Regards, Sean.

    Read the article

  • Problem Implementing StructureMap in VB.Net Conversion of SharpArchitecture

    - by Monkeeman69
    I work in a VB.Net environment and have recently been tasked with creating an MVC enviroment to use as a base to work from. I decided to convert the latest SharpArchitecture release (Q3 2009) into VB, which on the whole has gone fine after a bit of hair pulling. I came across a problem with Castle Windsor where my custom repository interface (lives in the core/domain project) that was reference in the constructor of my test controller was not getting injected with the concrete implementation (from the data project). I hit a brick wall with this so basically decided to switch out Castle Windsor for StructureMap. I think I have implemented this ok as everything compiles and runs and my controller ran ok when referencing a custom repository interface. It appears now that I have/or cannot now setup my generic interfaces up properly (I hope this makes sense so far as I am new to all this). When I use IRepository(Of T) (wanting it to be injected with a concrete implementation of Repository(Of Type)) in the controller constructor I am getting the following runtime error: "StructureMap Exception Code: 202 No Default Instance defined for PluginFamily SharpArch.Core.PersistenceSupport.IRepository`1[[DebtRemedy.Core.Page, DebtRemedy.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], SharpArch.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b5f559ae0ac4e006" Here are my code excerpts that I am using (my project is called DebtRemedy). My structuremap registry class Public Class DefaultRegistry Inherits Registry Public Sub New() ''//Generic Repositories AddGenericRepositories() ''//Custom Repositories AddCustomRepositories() ''//Application Services AddApplicationServices() ''//Validator [For](GetType(IValidator)).Use(GetType(Validator)) End Sub Private Sub AddGenericRepositories() ''//ForRequestedType(GetType(IRepository(Of ))).TheDefaultIsConcreteType(GetType(Repository(Of ))) [For](GetType(IEntityDuplicateChecker)).Use(GetType(EntityDuplicateChecker)) [For](GetType(IRepository(Of ))).Use(GetType(Repository(Of ))) [For](GetType(INHibernateRepository(Of ))).Use(GetType(NHibernateRepository(Of ))) [For](GetType(IRepositoryWithTypedId(Of ,))).Use(GetType(RepositoryWithTypedId(Of ,))) [For](GetType(INHibernateRepositoryWithTypedId(Of ,))).Use(GetType(NHibernateRepositoryWithTypedId(Of ,))) End Sub Private Sub AddCustomRepositories() Scan(AddressOf SetupCustomRepositories) End Sub Private Shared Sub SetupCustomRepositories(ByVal y As IAssemblyScanner) y.Assembly("DebtRemedy.Core") y.Assembly("DebtRemedy.Data") y.WithDefaultConventions() End Sub Private Sub AddApplicationServices() Scan(AddressOf SetupApplicationServices) End Sub Private Shared Sub SetupApplicationServices(ByVal y As IAssemblyScanner) y.Assembly("DebtRemedy.ApplicationServices") y.With(New FirstInterfaceConvention) End Sub End Class Public Class FirstInterfaceConvention Implements ITypeScanner Public Sub Process(ByVal type As Type, ByVal graph As PluginGraph) Implements ITypeScanner.Process If Not IsConcrete(type) Then Exit Sub End If ''//only works on concrete types Dim firstinterface = type.GetInterfaces().FirstOrDefault() ''//grabs first interface If firstinterface IsNot Nothing Then graph.AddType(firstinterface, type) Else ''//registers type ''//adds concrete types with no interfaces graph.AddType(type) End If End Sub End Class I have tried both ForRequestedType (which I think is now deprecated) and For. IRepository(Of T) lives in SharpArch.Core.PersistenceSupport. Repository(Of T) lives in SharpArch.Data.NHibernate. My servicelocator class Public Class StructureMapServiceLocator Inherits ServiceLocatorImplBase Private container As IContainer Public Sub New(ByVal container As IContainer) Me.container = container End Sub Protected Overloads Overrides Function DoGetInstance(ByVal serviceType As Type, ByVal key As String) As Object Return If(String.IsNullOrEmpty(key), container.GetInstance(serviceType), container.GetInstance(serviceType, key)) End Function Protected Overloads Overrides Function DoGetAllInstances(ByVal serviceType As Type) As IEnumerable(Of Object) Dim objList As New List(Of Object) For Each obj As Object In container.GetAllInstances(serviceType) objList.Add(obj) Next Return objList End Function End Class My controllerfactory class Public Class ServiceLocatorControllerFactory Inherits DefaultControllerFactory Protected Overloads Overrides Function GetControllerInstance(ByVal requestContext As RequestContext, ByVal controllerType As Type) As IController If controllerType Is Nothing Then Return Nothing End If Try Return TryCast(ObjectFactory.GetInstance(controllerType), Controller) Catch generatedExceptionName As StructureMapException System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave()) Throw End Try End Function End Class The initialise stuff in my gloabal.asax Dim container As IContainer = New Container(New DefaultRegistry) ControllerBuilder.Current.SetControllerFactory(New ServiceLocatorControllerFactory()) ServiceLocator.SetLocatorProvider(Function() New StructureMapServiceLocator(container)) My test controller Public Class DataCaptureController Inherits BaseController Private ReadOnly clientRepository As IClientRepository() Private ReadOnly pageRepository As IRepository(Of Page) Public Sub New(ByVal clientRepository As IClientRepository(), ByVal pageRepository As IRepository(Of Page)) Check.Require(clientRepository IsNot Nothing, "clientRepository may not be null") Check.Require(pageRepository IsNot Nothing, "pageRepository may not be null") Me.clientRepository = clientRepository Me.pageRepository = pageRepository End Sub Function Index() As ActionResult Return View() End Function The above works fine when I take out everything to do with the pageRepository which is IRepository(Of T). Any help with this would be greatly appreciated.

    Read the article

  • asp.net mvc - How to create fake test objects quickly and efficiently

    - by Simon G
    Hi, I'm currently testing the controller in my mvc app and I'm creating a fake repository for testing. However I seem to be writing more code and spending more time for the fakes than I do on the actual repositories. Is this right? The code I have is as follows: Controller public partial class SomeController : Controller { IRepository repository; public SomeController(IRepository rep) { repository = rep; } public virtaul ActionResult Index() { // Some logic var model = repository.GetSomething(); return View(model); } } IRepository public interface IRepository { Something GetSomething(); } Fake Repository public class FakeRepository : IRepository { private List<Something> somethingList; public FakeRepository(List<Something> somethings) { somthingList = somthings; } public Something GetSomething() { return somethingList; } } Fake Data class FakeSomethingData { public static List<Something> CreateSomethingData() { var somethings = new List<Something>(); for (int i = 0; i < 100; i++) { somethings.Add(new Something { value1 = String.Format("value{0}", i), value2 = String.Format("value{0}", i), value3 = String.Format("value{0}", i) }); } return somethings; } } Actual Test [TestClass] public class SomethingControllerTest { SomethingController CreateSomethingController() { var testData = FakeSomethingData.CreateSomethingData(); var repository = new FakeSomethingRepository(testData); SomethingController controller = new SomethingController(repository); return controller; } [TestMethod] public void SomeTest() { // Arrange var controller = CreateSomethingController(); // Act // Some test here // Arrange } } All this seems to be a lot of extra code, especially as I have more than one repository. Is there a more efficient way of doing this? Maybe using mocks? Thanks

    Read the article

  • Generics and reflection in Java

    - by Ragesh
    This is probably a very basic question, but I'm really new to generics in Java and I'm having a hard time altering my thought process from the way things are done in C#, so bear with me. I'm trying to build a generic repository in Java. I've created an IRepository interface that looks like this: public interface IRepository<T extends IEntity> And a Repository class that looks like this: public class Repository<T extends IEntity> implements IRepository<T> Now, from within the constructor of my Repository class, I'd like to be able to "divine" the exact type of T. For example, if I instantiated a repository like this: IRepository<MyClass> repo = new Repository<MyClass>(); I'd like to know that T is actually MyClass. This is trivial in C#, but obviously generics are a totally different beast in Java and I can't seem to find anything that would help me do this.

    Read the article

  • Project Naming Convention Feedback Please

    - by Sam Striano
    I am creating a ASP.NET MVC 3 application using Entity Framework 4. I am using the Repository/Service Pattern and was looking for feedback. I currently have the following: MVC Application (GTG.dll) GTG GTG.Controllers GTG.ViewModels Business POCO's (GTG.Business.dll) This contains all business objects (Customer, Order, Invoice, etc...) EF Model/Repositories (GTG.Data.dll) GTG.Business (GTG.Context.tt) I used the Entity POCO Generator Templates. GTG.Data.Repositories Service Layer (GTG.Data.Services.dll) GTG.Data.Services - Contains all of the service objects, one per aggregate root. The following is a little sample code: Controller Namespace Controllers Public Class HomeController Inherits System.Web.Mvc.Controller Function Index() As ActionResult Return View(New Models.HomeViewModel) End Function End Class End Namespace Model Namespace Models Public Class HomeViewModel Private _Service As CustomerService Public Property Customers As List(Of Customer) Public Sub New() _Service = New CustomerService _Customers = _Service.GetCustomersByBusinessName("Striano") End Sub End Class End Namespace Service Public Class CustomerService Private _Repository As ICustomerRepository Public Sub New() _Repository = New CustomerRepository End Sub Function GetCustomerByID(ByVal ID As Integer) As Customer Return _Repository.GetByID(ID) End Function Function GetCustomersByBusinessName(ByVal Name As String) As List(Of Customer) Return _Repository.Query(Function(x) x.CompanyName.StartsWith(Name)).ToList End Function End Class Repository Namespace Data.Repositories Public Class CustomerRepository Implements ICustomerRepository Public Sub Add(ByVal Entity As Business.Customer) Implements IRepository(Of Business.Customer).Add End Sub Public Sub Delete(ByVal Entity As Business.Customer) Implements IRepository(Of Business.Customer).Delete End Sub Public Function GetByID(ByVal ID As Integer) As Business.Customer Implements IRepository(Of Business.Customer).GetByID Using db As New GTGContainer Return db.Customers.FirstOrDefault(Function(x) x.ID = ID) End Using End Function Public Function Query(ByVal Predicate As System.Linq.Expressions.Expression(Of System.Func(Of Business.Customer, Boolean))) As System.Linq.IQueryable(Of Business.Customer) Implements IRepository(Of Business.Customer).Query Using db As New GTGContainer Return db.Customers.Where(Predicate) End Using End Function Public Sub Save(ByVal Entity As Business.Customer) Implements IRepository(Of Business.Customer).Save End Sub End Class End Namespace

    Read the article

  • Unity and Object Creation

    - by William
    I am using unity as my IoC container. I am trying to implement a type of IProviderRepository. The concrete implementation has a constructor that accepts a type of IRepository. When I remove the constructor parameter from the concrete implementation everything works fine. I am sure the container is wired correctly. When I try to create the concrete object with the constructor I receive the following error: "The current build operation (build key Build Key[EMRGen.Infrastructure.Data.IRepository1[EMRGen.Model.Provider.Provider], null]) failed: The current type, EMRGen.Infrastructure.Data.IRepository1[EMRGen.Model.Provider.Provider], is an interface and cannot be constructed. Are you missing a type mapping? (Strategy type BuildPlanStrategy, index 3)". Is it possible to achieve the above mention functionality with Unity? Namely have Unity infer a concrete type from the Interface and also inject the constructor of the concrete type with the appropriate concrete object based on constructor parameters. Below is sample of my types defined in Unity and a skeleton class listing for what I want to achieve. IProviderRepository is implemented by ProviderRepository which has a constructor that expects a type of IRepository. <typeAlias alias="ProviderRepositoryInterface" type="EMRGen.Model.Provider.IProviderRepository, EMRGen.Model" /> <typeAlias alias="ProviderRepositoryConcrete" type="EMRGen.Infrastructure.Repositories.Providers.ProviderRepository, EMRGen.Infrastructure.Repositories" /> <typeAlias alias="ProviderGenericRepositoryInterface" type="EMRGen.Infrastructure.Data.IRepository`1[[EMRGen.Model.Provider.IProvider, EMRGen.Model]], EMRGen.Infrastructure" /> <typeAlias alias="ProviderGenericRepositoryConcrete" type="EMRGen.Infrastructure.Repositories.EntityFramework.ApplicationRepository`1[[EMRGen.Model.Provider.Provider, EMRGen.Model]], EMRGen.Infrastructure.Repositories" /> <!-- Provider Mapping--> <typeAlias alias="ProviderInterface" type="EMRGen.Model.Provider.IProvider, EMRGen.Model" /> <typeAlias alias="ProviderConcrete" type="EMRGen.Model.Provider.Doctor, EMRGen.Model" /> //Illustrate the call being made inside my class public class PrescriptionService { PrescriptionService() { IUnityContainer uc = UnitySingleton.Instance.Container; UnityServiceLocator unityServiceLocator = new UnityServiceLocator(uc); ServiceLocator.SetLocatorProvider(() => unityServiceLocator); IProviderRepository pRepository = ServiceLocator.Current.GetInstance<IProviderRepository>(); } } public class GenericRepository<IProvider> : IRepository<IProvider> { } public class ProviderRepository : IProviderRepository { private IRepository<IProvider> _genericProviderRepository; //Explict public default constructor public ProviderRepository(IRepository<IProvider> genericProviderRepository) { _genericProviderRepository = genericProviderRepository; } }

    Read the article

  • Advantage of creating a generic repository vs. specific repository for each object?

    - by LuckyLindy
    We are developing an ASP.NET MVC application, and are now building the repository/service classes. I'm wondering if there are any major advantages to creating a generic IRepository interface that all repositories implement, vs. each Repository having its own unique interface and set of methods. For example: a generic IRepository interface might look like (taken from this answer): public interface IRepository : IDisposable { T[] GetAll<T>(); T[] GetAll<T>(Expression<Func<T, bool>> filter); T GetSingle<T>(Expression<Func<T, bool>> filter); T GetSingle<T>(Expression<Func<T, bool>> filter, List<Expression<Func<T, object>>> subSelectors); void Delete<T>(T entity); void Add<T>(T entity); int SaveChanges(); DbTransaction BeginTransaction(); } Each Repository would implement this interface (e.g. CustomerRepository:IRepository, ProductRepository:IRepository, etc). The alternate that we've followed in prior projects would be: public interface IInvoiceRepository : IDisposable { EntityCollection<InvoiceEntity> GetAllInvoices(int accountId); EntityCollection<InvoiceEntity> GetAllInvoices(DateTime theDate); InvoiceEntity GetSingleInvoice(int id, bool doFetchRelated); InvoiceEntity GetSingleInvoice(DateTime invoiceDate, int accountId); //unique InvoiceEntity CreateInvoice(); InvoiceLineEntity CreateInvoiceLine(); void SaveChanges(InvoiceEntity); //handles inserts or updates void DeleteInvoice(InvoiceEntity); void DeleteInvoiceLine(InvoiceLineEntity); } In the second case, the expressions (LINQ or otherwise) would be entirely contained in the Repository implementation, whoever is implementing the service just needs to know which repository function to call. I guess I don't see the advantage of writing all the expression syntax in the service class and passing to the repository. Wouldn't this mean easy-to-messup LINQ code is being duplicated in many cases? For example, in our old invoicing system, we call InvoiceRepository.GetSingleInvoice(DateTime invoiceDate, int accountId) from a few different services (Customer, Invoice, Account, etc). That seems much cleaner than writing the following in multiple places: rep.GetSingle(x => x.AccountId = someId && x.InvoiceDate = someDate.Date); The only disadvantage I see to using the specific approach is that we could end up with many permutations of Get* functions, but this still seems preferable to pushing the expression logic up into the Service classes. What am I missing?

    Read the article

  • Problem resolving a generic Repository with Entity Framework and Castle Windsor Container

    - by user368776
    Hi, im working in a generic repository implementarion with EF v4, the repository must be resolved by Windsor Container. First the interface public interface IRepository<T> { void Add(T entity); void Delete(T entity); T Find(int key) } Then a concrete class implements the interface public class Repository<T> : IRepository<T> where T: class { private IObjectSet<T> _objectSet; } So i need _objectSet to do stuff like this in the previous class public void Add(T entity) { _objectSet.AddObject(entity); } And now the problem, as you can see im using a EF interface like IObjectSet to do the work, but this type requires a constraint for the T generic type "where T: class". That constrait is causing an exception when Windsor tries to resolve its concrete type. Windsor configuration look like this. <castle> <components> <component id="LVRepository" service="Repository.Infraestructure.IRepository`1, Repository" type="Repository.Infraestructure.Repository`1, Repository" lifestyle="transient"> </component> </components> The container resolve code IRepository<Product> productsRep =_container.Resolve<IRepository<Product>>(); Now the exception im gettin System.ArgumentException: GenericArguments[0], 'T', on 'Repository.Infraestructure.Repository`1[T]' violates the constraint of type 'T'. ---> System.TypeLoadException: GenericArguments[0], 'T', on 'Repository.Infraestructure.Repository`1[T]' violates the constraint of type parameter 'T'. If i remove the constraint in the concrete class and the depedency on IObjectSet (if i dont do it get a compile error) everything works FINE, so i dont think is a container issue, but IObjectSet is a MUST in the implementation. Some help with this, please.

    Read the article

  • VS2010 Implement Generic Interface expansion doesn't use specified type

    - by TJB
    Using the release version of Visual Studio 2010 I think there's a difference in the "Implement Interface" expansion from VS2008 If I speicify an interface and implement it in a class as so: public interface IRepository<T> where T : IModel { T Get<T>(int id); void Update<T>(); int Add<T>(T item); } public class MockRepository : IRepository<MockUser> { // ... } Then use the "Implement Interface" expansion and get this: public class MockRepository : IRepository<MockUser> { public T Get<T>(int id) { throw new NotImplementedException(); } public void Update<T>() { throw new NotImplementedException(); } public int Add<T>(T item) { throw new NotImplementedException(); } } Instead of what I expected public class MockRepository : IRepository<MockUser> { public MockUser Get<MockUser>(int id) { throw new NotImplementedException(); } public void Update<MockUser>() { throw new NotImplementedException(); } public int Add<MockUser>(MockUser item) { throw new NotImplementedException(); } } The IDE uses the type variable name from the generic interface definition T instead of the specified concrete type MockUser. Is this a bug? Or is something new just for VS2010 / .Net 4.0?

    Read the article

  • Unit testing with Mocks. Test behaviour not implementation

    - by Kenny Eliasson
    Hi.. I always had a problem when unit testing classes that calls other classes, for example I have a class that creates a new user from a phone-number then saves it to the database and sends a SMS to the number provided. Like the code provided below. public class UserRegistrationProcess : IUserRegistration { private readonly IRepository _repository; private readonly ISmsService _smsService; public UserRegistrationProcess(IRepository repository, ISmsService smsService) { _repository = repository; _smsService = smsService; } public void Register(string phone) { var user = new User(phone); _repository.Save(user); _smsService.Send(phone, "Welcome", "Message!"); } } It is a really simple class but how would you go about and test it? At the moment im using Mocks but I dont really like it [Test] public void WhenRegistreringANewUser_TheNewUserIsSavedToTheDatabase() { var repository = new Mock<IRepository>(); var smsService = new Mock<ISmsService>(); var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object); var phone = "0768524440"; userRegistration.Register(phone); repository.Verify(x => x.Save(It.Is<User>(user => user.Phone == phone)), Times.Once()); } [Test] public void WhenRegistreringANewUser_ItWillSendANewSms() { var repository = new Mock<IRepository>(); var smsService = new Mock<ISmsService>(); var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object); var phone = "0768524440"; userRegistration.Register(phone); smsService.Verify(x => x.Send(phone, It.IsAny<string>(), It.IsAny<string>()), Times.Once()); } It feels like I am testing the wrong thing here? Any thoughts on how to make this better?

    Read the article

  • C# Multiple constraints

    - by John
    I have an application with lots of generics and IoC. I have an interface like this: public interface IRepository<TType, TKeyType> : IRepo Then I have a bunch of tests for my different implementations of IRepository. Many of the objects have dependencies on other objects so for the purpose of testing I want to just grab one that is valid. I can define a separate method for each of them: public static EmailType GetEmailType() { return ContainerManager.Container.Resolve<IEmailTypeRepository>().GetList().FirstOrDefault(); } But I want to make this generic so it can by used to get any object from the repository it works with. I defined this: public static R GetItem<T, R>() where T : IRepository<R, int> { return ContainerManager.Container.Resolve<T>().GetList().FirstOrDefault(); } This works fine for the implementations that use an integer for the key. But I also have repositories that use string. So, I do this now: public static R GetItem<T, R, W>() where T : IRepository<R, W> This works fine. But I'd like to restrict 'W' to either int or string. Is there a way to do that? The shortest question is, can I constrain a generic parameter to one of multiple types?

    Read the article

1 2 3 4 5  | Next Page >