How use Bounded Context Pattern in AspnetBoilerplate - aspnetboilerplate

How use Bounded Context Pattern in AspnetBoilerplate, Is there any way to use to use Bounded Context Pattern in AspnetBoilerplate?

Connect with multiple database in ASP.NET ZERO/ASP.NET BOILERPLATE.
Note - Use seperate DB Context to use multiple Databases.
Step 1. Create modal class in "MultipleDbContextEfCoreDemo.Core" Project for your tables.
[Table ("tblStudent")] //Is in First Database
public class Student : Entity<long> {
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
protected Student () { }
}
[Table ("tblCourses")] //Is in Second Database
public class Courses : Entity<long> {
public int ID { get; set; }
public string CourseName { get; set; }
public string Standard { get; set; }
protected Courses () { }
}
Step 2. In same project("MultipleDbContextEfCoreDemo.Core" Project) create/use "MultipleDbContextEfCoreDemoConsts.cs" file to add Database Connection names.
public class MultipleDbContextEfCoreDemoConsts
{
public const string LocalizationSourceName = "MultipleDbContextEfCoreDemo";
public const string ConnectionStringName = "Default";
public const string SecondDbConnectionStringName = "Second";
}
Step 3. In "MultipleDbContextEfCoreDemo.EntityFrameworkCore" Project goto "EntityFrameworkCore" Folder and create individual "DBContext" and "DbContextConfigurer" file for each database connection to which you want to connect.
FirstDatabase Setting -
required files to connect to first db -
1. FirstDbContext.cs
public class FirstDbContext : AbpDbContext, IAbpPersistedGrantDbContext {
/* Define an IDbSet for each entity of the application */
public DbSet<PersistedGrantEntity> PersistedGrants { get; set; }
public virtual DbSet<Student> Student { get; set; }
public FirstDbContext (DbContextOptions<FirstDbContext> options) : base (options) {
}
protected override void OnModelCreating (ModelBuilder modelBuilder) { }
}
2. FirstDbContextConfigurer
public static class FirstDbContextConfigurer {
public static void Configure (DbContextOptionsBuilder<FirstDbContext> builder, string connectionString) {
builder.UseSqlServer (connectionString);
}
public static void Configure (DbContextOptionsBuilder<FirstDbContext> builder, DbConnection connection) {
builder.UseSqlServer (connection);
}
}
SecondDatabase Setting -
required files to connect to second db -
1. SecondDbContext.cs
public class SecondDbContext : AbpDbContext, IAbpPersistedGrantDbContext {
/* Define an IDbSet for each entity of the application */
public DbSet<PersistedGrantEntity> PersistedGrants { get; set; }
public virtual DbSet<Student> Student { get; set; }
public SecondDbContext (DbContextOptions<SecondDbContext> options) : base (options) {
}
protected override void OnModelCreating (ModelBuilder modelBuilder) { }
}
2. SecondDbContextConfigurer
public static class SecondDbContextConfigurer {
public static void Configure (DbContextOptionsBuilder<SecondDbContext> builder, string connectionString) {
builder.UseSqlServer (connectionString);
}
public static void Configure (DbContextOptionsBuilder<SecondDbContext> builder, DbConnection connection) {
builder.UseSqlServer (connection);
}
}
Step 4. Then in same project("MultipleDbContextEfCoreDemo.EntityFrameworkCore") add "MyConnectionStringResolver.cs"
public class MyConnectionStringResolver : DefaultConnectionStringResolver
{
public MyConnectionStringResolver(IAbpStartupConfiguration configuration)
: base(configuration)
{
}
public override string GetNameOrConnectionString(ConnectionStringResolveArgs args)
{
if (args["DbContextConcreteType"] as Type == typeof(SecondDbContext))
{
var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
return configuration.GetConnectionString(MultipleDbContextEfCoreDemoConsts.SecondDbConnectionStringName);
}
return base.GetNameOrConnectionString(args);
}
}
Step 5. Then in same project("MultipleDbContextEfCoreDemo.EntityFrameworkCore"), Update "MultipleDbContextEfCoreDemoEntityFrameworkCoreModule.cs" file to replace the "IConnectionStringResolver" with our custom implementation MyConnectionStringResolver.
[DependsOn(typeof(MultipleDbContextEfCoreDemoCoreModule), typeof(AbpEntityFrameworkCoreModule))]
public class MultipleDbContextEfCoreDemoEntityFrameworkCoreModule : AbpModule
{
public override void PreInitialize()
{
Configuration.ReplaceService<IConnectionStringResolver, MyConnectionStringResolver>();
// Configure first DbContext
Configuration.Modules.AbpEfCore().AddDbContext<FirstDbContext>(options =>
{
if (options.ExistingConnection != null)
{
FirstDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
}
else
{
FirstDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
}
});
// Configure second DbContext
Configuration.Modules.AbpEfCore().AddDbContext<SecondDbContext>(options =>
{
if (options.ExistingConnection != null)
{
SecondDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
}
else
{
SecondDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
}
});
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(MultipleDbContextEfCoreDemoEntityFrameworkCoreModule).GetAssembly());
}
}
Step 6. Create the Service in "MultipleDbContextEfCoreDemo.Application" project with Dto, Interface and Service Class.
ITestAppService.cs-
public interface ITestAppService : IApplicationService
{
List<string> GetStudentAndCourses();
}
TestAppService.cs
public class TestAppService : MultipleDbContextEfCoreDemoAppServiceBase, ITestAppService
{
private readonly IRepository<Student> _studentRepository; //in the first db
private readonly IRepository<Courses> _coursesRepository; //in the second db
public TestAppService(
IRepository<Student> studentRepository,
IRepository<Courses> coursesRepository
)
{
_studentRepository = studentRepository;
_coursesRepository = coursesRepository;
}
//a sample method uses both databases concurrently
public List<string> GetStudentAndCourses()
{
List<string> names = new List<string>();
var studentNames = _studentRepository.GetAllList().Select(p => "Student: " + p.FirstName).ToList();
names.AddRange(peopleNames);
var courseNames = _coursesRepository.GetAllList().Select(p => "Course: " + p.CourseName).ToList();
names.AddRange(courseNames);
return names;
}
}
Step 7. Add Database connectionStrings to your MultipleDbContextEfCoreDemo.Web/MultipleDbContextEfCoreDemo.Web.Host project's
"appsettings.json" file.
{
"ConnectionStrings": {
"Default":
"Server=XXX.XXX.XX.XX;Database=firstDB;Integrated Security=False;TrustServerCertificate=True;User ID=XX;Password=XXX;",
"Second":
"Server=XXX.XXX.XX.XX;Database=secondDB;Integrated Security=False;TrustServerCertificate=True;User ID=XX;Password=XXX;"
}
}
Step 8. Use Service in your angular/MVC project.

With EF you need one complete dbcontext for migrations.
Create other "bounded" dbcontext, with the entities to be ignored in modelbuilder, then use this in appservice.
Very simple answer
HTH

Related

System.AggregateException: Some services are not able to be constructed (Error while validating the service ..'ServiceType: MediatR.IRequestHandler

My CQRS file layout is as in the picture. Whenever I enable the handler inside the GetAllBooks folder, I get an error.
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler2[BookAPI.Application.Features.Queries.Book.GetAllBooks.GetAllBookQueryRequest,System.Collections.Generic.List1[BookAPI.Application.Features.Queries.Book.GetAllBooks.GetAllBookQueryResponse]] Lifetime: Transient ImplementationType: BookAPI.Application.Features.Queries.Book.GetAllBooks.GetAllBookQueryHandler': Unable to resolve service for type 'BookAPI.Application.Repositories.IBookReadRepository' while attempting to activate 'BookAPI.Application.Features.Queries.Book.GetAllBooks.GetAllBookQueryHandler'.)
GetAllBookQueryHandler
public class GetAllBookQueryHandler : IRequestHandler<GetAllBookQueryRequest, List<GetAllBookQueryResponse>>
{
private IBookReadRepository bookReadRepository;
public GetAllBookQueryHandler(IBookReadRepository bookReadRepository)
{
this.bookReadRepository = bookReadRepository;
}
public async Task<List<GetAllBookQueryResponse>> Handle(GetAllBookQueryRequest request, CancellationToken cancellationToken)
{
List<B.Book> books = bookReadRepository.GetAll().Include(x=>x.Authors).Include(x=>x.Category).Include(x=>x.BookImages).ToList();
List<GetAllBookQueryResponse> responses = new();
foreach (B.Book book in books)
{
responses.Add(
new GetAllBookQueryResponse
{
Name= book.Name,
CategoryName=book.Category.Name,
AuthorName=book.Authors.First().Name,
Img=book.BookImages.First().Path,
UnitPrice=book.UnitPrice,
}
);
}
return responses;
}
}
GetAllBookQueryRequest
public class GetAllBookQueryRequest : IRequest<List<GetAllBookQueryResponse>>
{
//This place is empty as all books are requested
}
GetAllBookQueryResponse
public class GetAllBookQueryResponse
{
public int Id { get; set; }
public string Name { get; set; }
public string CategoryName { get; set; }
public string AuthorName { get; set; }
public string Img { get; set; }
public ushort UnitPrice { get; set; }
}
ServiceRegistration for IoC
using MediatR;
using Microsoft.Extensions.DependencyInjection;
namespace BookAPI.Application
{
public static class ServiceRegistration
{
public static void AddApplicationServices(this IServiceCollection services)
{
//find all handler, request and response and add IoC
services.AddMediatR(typeof(ServiceRegistration));
services.AddHttpClient();
}
}
}
Program.cs
I add services
builder.Services.AddApplicationServices();
Book Controller
.
.
.
readonly IMediator mediator;
public BookController(IBookWriteRepository bookWriteRepository, IWebHostEnvironment webHostEnvironment, IFileService fileService, IMediator mediator)
{
bookWriteRepository = bookWriteRepository;
_fileService = fileService;
this.mediator = mediator;
}
[HttpGet]
public async Task<IActionResult> GetAllBooks([FromQuery] GetAllBookQueryRequest getAllBookQueryRequest)
{
return Ok(await mediator.Send(getAllBookQueryRequest));
}
.
.
.
I guess it doesn't see the service I introduced, but I don't understand why GetAllBookHandler is throwing an error in the operation and not the others. For example, my handlers that list and create customers are working.

ASPNET Boilerplate, extending audit log

I am trying to extend the AuditLog entity in ASPNETBOILETPLATE framework in order to add some new properties to it. I have tried to extend the AuditLog class (ExtendedAuditInfo) and implement a customised version of AuditStore Class (ExtendedAuditStore). However, I am not able to inject my new ExtendedAuditInfo in the constructor and receive two error messages regarding unmatching input parameters in the Constructor and SaveAsync method.
Class ExtendedAuditInfo:
public class ExtendedAuditInfo : AuditInfo
{
// Some properties
}
Class ExtendedAuditStore:
public class ExtendedAuditStore : AuditingStore
{
public ExtendedAuditStore(IRepository<ExtendedAuditInfo, long> auditLogRepository)
: base(auditLogRepository)
{
}
public override Task SaveAsync(ExtendedAuditInfo auditInfo)
{
if (!string.IsNullOrEmpty(auditInfo.Parameters) && auditInfo.Parameters != "{}")
{
var parameters = JsonConvert.DeserializeObject<AuditParameterInput>(auditInfo.Parameters);
if (parameters != null)
auditInfo.CustomData = parameters.Input.Id.ToString();
}
return base.SaveAsync(auditInfo);
}
}
The errors are:
cannot convert from 'Abp.Domain.Repositories.IRepository<SixB.Serafina.Auditing.ExtendedAuditInfo, long>' to 'Abp.Domain.Repositories.IRepository<Abp.Auditing.AuditLog, long>'
and
no suitable method found to override
The procedure above is based on the idea that I found Here
I found the solution based on the official document of How To Extend Existing Entities.
In order to extend the AuditLog class, inheritance must be used. Therefore a new class, let's say ExtendedAuditInfo needs to be inherited from AuditLog.
public class ExtendedAuditLog : AuditLog
{
public ExtendedAuditLog()
{
}
public ExtendedAuditLog(AuditInfo auditInfo)
{
this.BrowserInfo = auditInfo.BrowserInfo;
this.ClientIpAddress = auditInfo.ClientIpAddress;
this.ClientName = auditInfo.ClientName;
this.CustomData = auditInfo.CustomData;
this.Exception = auditInfo.Exception?.Message.ToString() + "";
this.ExecutionDuration = auditInfo.ExecutionDuration;
this.ExecutionTime = auditInfo.ExecutionTime;
this.ImpersonatorTenantId = auditInfo.ImpersonatorTenantId;
this.ImpersonatorUserId = auditInfo.ImpersonatorUserId;
this.MethodName = auditInfo.MethodName;
this.Parameters = auditInfo.Parameters;
this.ReturnValue = auditInfo.ReturnValue;
this.ServiceName = auditInfo.ServiceName;
this.TenantId = auditInfo.TenantId;
this.UserId = auditInfo.UserId;
}
//new properties
}
This class has to be added to the context and obviously, a new migration needs to be run in order to add the new properties.
public class ProjectDbContext : AbpZeroDbContext<Tenant, Role, User, ProjectDbContext >
{
/* Define a DbSet for each entity of the application */
public SerafinaDbContext(DbContextOptions<SerafinaDbContext> options)
: base(options)
{
}
public virtual DbSet<County> Counties { get; set; }
public virtual DbSet<Country> Countries { get; set; }
public virtual DbSet<Currency> Currencies { get; set; }
public virtual DbSet<OrganisationType> OrganisationTypes { get; set; }
public virtual DbSet<ExtendedAuditLog> ExtendedAuditLogs { get; set; }
}
Finally, in the ExtendedAuditStore class, IRepository<ExtendedAuditLog, long> _extendedAuditLogRepository has to be injected as a second parameter of the constructor and can be used to insert the extended entity.
public class ExtendedAuditStore : AuditingStore
{
IRepository<ExtendedAuditLog, long> _extendedAuditLogRepository;
public ExtendedAuditStore(
IRepository<AuditLog, long> auditLogRepository,
IRepository<ExtendedAuditLog, long> extendedAuditLogRepository
)
: base(auditLogRepository)
{
_extendedAuditLogRepository = extendedAuditLogRepository;
}
public override async Task SaveAsync(AuditInfo auditInfo)
{
if (auditInfo.Exception != null)
await base.SaveAsync(auditInfo);
var auditLog = new ExtendedAuditLog(auditInfo);
//new properties can be set here
await _extendedAuditLogRepository.InsertAsync(auditLog);
}
}
Also, instead of inheriting from AuditingStore, a new implementation for IAuditingStore can be created and injected into application services.
UPDATE:
Finally, all you need is to replace the default AuditingStore in StartUp class:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddTransient<IAuditingStore, ExtendedAuditStore>();
}

Options are not passed to the class

I'm trying to pass options to the class via the constructor from the appsettings.json file.
The file itself looks like this:
"IDP": {
"UrlCbr": "https://www.cbr-xml-daily.ru/daily_json.js",
"UrlDadata": "https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/currency",
"DadataToken": "94dabe1e8342c21fdad9622be29514d4f0f99bbd8",
"BotToken": "1549046386:AAHJsdsaMVaCT-8O3D_P8VLxw6EKAr4P9JfSU",
"BotName": "Hop_hipBot",
"BotUrl": "https://111295d46c69.ngrok.io/{0}"
}
To do this, I created the IDP.cs class:
public class IDP
{
public string UrlCbr { get; set; }
public string UrlDadata { get; set; }
public string DadataToken { get; set; }
public string BotToken { get; set; }
public string BotName { get; set; }
public string BotUrl { get; set; }
}
Then in the Startup.cs I'm making a connection:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews().AddNewtonsoftJson();
services.Configure<IDP>(Configuration.GetSection("IDP"));
}
I need this data in the implementation of the bot:
class Bot
{
private static TelegramBotClient botClient;
private static IOptions<IDP> _IDPs;
public void Temp(IOptions<IDP> IDPs)
{
_IDPs = IDPs;
}
public static async Task<TelegramBotClient> GetBotClientAsync()
{
if (botClient != null)
{
return botClient;
}
botClient = new TelegramBotClient(_IDPs.Value.BotToken);
var hook = string.Format(_IDPs.Value.BotUrl, #"api/bot");
await botClient.SetWebhookAsync(hook);
return botClient;
}
}
Well, the bot itself is launched in Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
Bot.GetBotClientAsync().Wait();
}
And when you run the entire application, the _IDPs field in the bot turns out to be null. Why is this happening and how do I need to properly deliver the data to the bot? In other classes, everything works correctly and options are passed
You have a bug in the Bot class. Change:
public void Temp(IOptions<IDP> IDPs)
{
_IDPs = IDPs;
}
To :
public class Bot
{
.....
private static IOptions<IDP> _IDPs;
public Bot(IOptions<IDP> IDPs)
{
_IDPs = IDPs;
}
......
}
Change your code like below:
public class Bot
{
private static IOptions<IDP> _IDPs;
public static void Temp(IOptions<IDP> IDPs)
{
_IDPs = IDPs;
}
public static async Task GetBotClientAsync()
{
var data = _IDPs.Value.BotToken;
}
}
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
//more services...
services.Configure<IDP>(Configuration.GetSection("IDP"));
var serviceProvider = services.BuildServiceProvider();
Bot.Temp(serviceProvider.GetService<IOptions<IDP>>());
Bot.GetBotClientAsync().Wait();
}
Result:

Why does NHibernate mapping-by-code ignore my Oracle-cased table name:

I am using an Oracle Database with NHibernate 3.3.2.4000.
I have a unit test set up to verify that an entity collection can be selected from the table. Here's what it looks like:
[TestFixture]
public class UnitOfWorkIntegrationTests
{
private IUnitOfWork _unitOfWork;
private INHibernateSessionFactory _nHibernateSessionFactory;
private IActiveSessionManager _activeSessionManager;
[SetUp]
public void BeforeEachTest()
{
_nHibernateSessionFactory = new NHibernateSessionFactory();
_activeSessionManager = new ActiveSessionManager();
_unitOfWork = new UnitOfWork(_nHibernateSessionFactory, _activeSessionManager);
}
[Test]
public void ShouldFetchOAuthMemberships()
{
var oauths = _unitOfWork.OAuthMemberships.ToArray();
oauths.ShouldNotBeNull();
}
}
The line that fetches my OAuthMemberships collection is throwing this exception:
could not execute query
[ select oauthmembe0_.id as id13_ from bckgrd_booklet_app.OAuthMembership oauthmembe0_ ]
[SQL: select oauthmembe0_.id as id13_ from bckgrd_booklet_app.OAuthMembership oauthmembe0_]
My OAuthMembership class and mapping are below. As you can see I am defining the table name as "OAUTH_MEMBERSHIP", but the generated SQL includes the camel-cased class name instead. I have no table name conventions defined. Why does NHibernate ignore my Oracle-cased table names?
public class OAuthMembership
{
public virtual int Id { get; set; }
public virtual string Provider { get; set; }
public virtual string ProviderUserId { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
public class OAuthMembershipMap : ClassMapping<OAuthMembership>
{
public void OAuthMembership()
{
Table("OAUTH_MEMBERSHIP");
Id(x => x.Id, m => m.Column("ID"));
Property(x => x.Provider, m => m.Column("PROVIDER"));
Property(x => x.ProviderUserId, m => m.Column("PROVIDER_USER_ID"));
ManyToOne(x => x.UserProfile, m => m.Column("USER_PROFILE_ID"));
}
}
Here's my NHibernateSessionFactory:
public interface INHibernateSessionFactory
{
ISession Create();
}
public class NHibernateSessionFactory : INHibernateSessionFactory
{
private static readonly ILog Log = LogManager.GetLogger(typeof(NHibernateSessionFactory).Name);
private readonly static ISessionFactory SessionFactory;
public static string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["MyConnection"].Return(x => x.ConnectionString,
"Data Source=myServer;User ID=bckgrd_booklet_app;Password=myPass;");
}
}
static NHibernateSessionFactory()
{
try
{
var mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
var configure = new NHibernate.Cfg.Configuration().Configure();
configure.AddMapping(domainMapping);
configure.BuildMappings();
configure.DataBaseIntegration(x =>
{
x.Driver<OracleClientDriver>();
x.Dialect<Oracle10gDialect>();
x.ConnectionStringName = ConnectionString;
})
.CurrentSessionContext<WebSessionContext>();
SessionFactory = configure.BuildSessionFactory();
}
catch (Exception ex)
{
Log.Error("NHibernateSessionFactory did not initialize correctly.", ex);
throw;
}
}
public ISession Create()
{
Log.Debug("Creating new session.");
return SessionFactory.OpenSession();
}
}
My ActiveSessionManager:
public interface IActiveSessionManager
{
void ClearActiveSession();
NHibernate.ISession GetActiveSession();
void SetActiveSession(NHibernate.ISession session);
}
public class ActiveSessionManager : IActiveSessionManager
{
[ThreadStatic]
private static ISession _current;
public ISession GetActiveSession()
{
return _current;
}
public void SetActiveSession(ISession session)
{
_current = session;
}
public void ClearActiveSession()
{
_current = null;
}
}
Relevant parts of my UnitOfWork definition:
public interface IUnitOfWork
{
//...
IQueryable<OAuthMembership> OAuthMemberships { get; }
IQueryable<T> All<T>();
//...
}
public class UnitOfWork : IUnitOfWork
{
private readonly ISession _session;
//...
public IQueryable<OAuthMembership> OAuthMemberships
{
get { return All<OAuthMembership>(); }
}
public UnitOfWork(
INHibernateSessionFactory sessionFactory,
IActiveSessionManager activeSessionManager)
{
_session = sessionFactory.Create();
activeSessionManager.SetActiveSession(_session);
}
public IQueryable<T> All<T>()
{
return _session.Query<T>();
}
//...
}
I found my error after adding Fluent NHibernate to my project and making the same error there.
My OAuthMembershipMap doesn't have a constructor. I had mistakenly added a void method called OAuthMembership instead, so my table mapping and my Id and Property mappings failed. See the corrected code:
public class OAuthMembershipMap : ClassMapping<OAuthMembership>
{
public OAuthMembershipMap()
{
Table("OAUTH_MEMBERSHIP");
Id(x => x.Id, m => m.Column("ID"));
Property(x => x.Provider, m => m.Column("PROVIDER"));
Property(x => x.ProviderUserId, m => m.Column("PROVIDER_USER_ID"));
ManyToOne(x => x.UserProfile, m => m.Column("USER_PROFILE_ID"));
}
}

Confusion over MVC3 Code First / Repositories

Please can someone help me because I am getting confused.
I have an Entity like this:
public class Code
{
public int ID { get; set; }
public int UserID { get; set; }
public string CodeText { get; set; }
}
and an Interface like this:
public interface ICodeRepository
{
IQueryable<Code> Codes { get; }
void AddCode(Code code);
void RemoveCode(Code code);
Code GetCodeById(int id);
}
and a Repository like this:
public class SQLCodeRepository : ICodeRepository
{
private EFSQLContext context;
public SQLCodeRepository()
{
context = new EFSQLContext();
}
public IQueryable<Code> Codes
{
get { return context.Codes; }
}
public void AddCode(Code code)
{
context.Codes.Add(code);
context.SaveChanges();
}
public void RemoveCode(Code code)
{
context.Codes.Remove(code);
context.SaveChanges();
}
public Code GetCodeById(int id)
{
return context.Codes.Where(x => x.ID == id).FirstOrDefault();
}
}
and a Context like this:
public class EFSQLContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Code> Codes { get; set; }
public DbSet<PortfolioUser> PortfolioUsers { get; set; }
}
If I declare my controller like this:
public class SearchController : Controller
{
private ICodeRepository cRepo;
public SearchController(ICodeRepository codeRepository)
{
cRepo = codeRepository;
}
}
and then try to do cRepo.GetCodeById(1) nothing happens. But if I declare private ICodeRepository rep = new SQLCodeRepository and then call rep.GetCodeById(1) I can see the method in the Repository being called.
What am I doing wrong?
It looks like from the constructor signature, you are going to be doing some dependency injection. The step you are missing is to set up a DI container using a tool like Castle Windsor. You then configure the MVC resolver to use the DI container to give you the correct implementation of ICodeRepository.
See this
You'll need to create a resolver that implements IDependencyResolver and IDependencyScope and a controller factory that inheritsDefaultControllerFactory
Once you have those you can do something like the following:
MyContainer container; // this needs to be a class level member of the asax
var configuration = GlobalConfiguration.Configuration;
container = new MyContainer() // may need additional stuff here depending on DI tool used
configuration.DependencyResolver = new MyDependancyResolver(container);
var mvcControllerFactory = new MyFactory(container.Kernel);
ControllerBuilder.Current.SetControllerFactory(mvcControllerFactory);
You would call the above code from the asax Application_Start()
See this answer for more specifics on using Ninject and MVC3

Resources