Define primitive resolve-time values in attribute on constructor parameter in DryIoC
In my code there's a dependency (MyDependency
) that I want to be resolved in a class (MyClass
). The dependency has a few dependencies itself as well as a primitive constructor parameter (primValue
), that should be defined by the resolving class. There are other classes besides MyClass
that also depend on MyDependency
, but they all use different values for primValue
.
public class MyDependency : ISpecificDependency
{
public Dependency(IDependencyA depA, IDependencyB depB, int primValue)
{
/*...*/
this.primValue = primValue;
}
}
public class MyClass
{
public MyClass(IDependencyC depC, IDependencyD depD, ISpecificDependency specDep)
{
/*...*/
this.specDep = specDep;
}
}
I know a way to do this would be to change the constructor of MyClass
as following, but that is pretty ugly because I try to inject the container itself as rarely as possible:
public MyClass(IDependencyC depC, IDependencyD depD, IContainer container)
{
/*...*/
this.specDep = container.Resolve<ISpecificDependency>(args: new object[] { 123 });
}
But my question is, if something like this could maybe also be achieved by using attributes. What I'm thinking of would be something similar to this:
public MyClass(IDependencyC depC, IDependencyD depD, [DependencyArguments(123)] ISpecificDependency specDep)
{
/*...*/
this.specDep = specDep;
}
Is something like that possible?
1 answer
-
answered 2022-05-04 13:48
dadhi
There are a couple of ways to provide the primitive value on resolution:
- Via
Func<MyPrimitiveType, MyService>
:container.Resolve<Func<int, MyClass>>()(123)
- Via global rule
container = container.WithDependencies(Parameters.Of.Type<int>(req => req.Parent.Any(p => p.ImplementationType == typeof(MyClass)) ? 123 : 42))
There are also a number of ways to specify the value on registration.
- Via
do you know?
how many words do you know
See also questions close to this topic
-
C# - Adding condition to func results in stack overflow exception
I have a func as part of specification class which sorts the given iqueryable
Func<IQueryable<T>, IOrderedQueryable<T>>? Sort { get; set; }
When i add more than one condition to the func like below , it results in stack overflow exception.
spec.OrderBy(sc => sc.Case.EndTime).OrderBy(sc => sc.Case.StartTime);
The OrderBy method is implemented like this
public ISpecification<T> OrderBy<TProperty>(Expression<Func<T, TProperty>> property) { _ = Sort == null ? Sort = items => items.OrderBy(property) : Sort = items => Sort(items).ThenBy(property); return this; }
Chaining or using separate lines doesn't make a difference.
This problem gets resolved if I assign a new instance of the specification and set it's func, but i don't want to be assigning to a new instance everytime. Please suggest what am i missing here and how to reuse the same instance (if possible).
-
How to projection fields for a dictionary (C#, MongdoDB)
I am trying my luck here, I have a model which is like the following
public class RowData : BaseBsonDefinition { . [BsonExtraElements] [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] public Dictionary<string, object> Rows { get; set; } = new(StringComparer.OrdinalIgnoreCase); . }
In result, the schema in the MongoDB looks like
{ "_id": { "$binary": { "base64": "HiuI1sgyT0OZmcgGUit2dw==", "subType": "03" } }, "c1": "AAA", "c8": "Fully Vac", "c10": "", }
Those c1, c8 and c10 fields are keys from the dictionary, my question is how to dynamic project those fields?
I tried
Builders<RowData>.Projection.Exclude(p => "c1")
It seems the MongoDB driver can not handle a value directly.
Anyone could point me in the correct direction?
Thanks,
-
How do I add new DataSource to an already Databinded CheckBoxList
i'm building a web form that show Database's item(Tables, Rows, FK,...)
I have a CheckBoxList of Tables (
chkListTable
) which will show a new CheckBoxList of Rows (chkListRow
) everytime I SelectedIndexChanged fromchkListTable
. The problem is i can show the items fromchkListTable
with 1 selected item. But i don't know how to showchkListRow
if multiple item fromchkListTable
are selected.Here are my codes:
aspx
:<div> <asp:Label ID="Label2" runat="server" Text="Table: "></asp:Label> <asp:CheckBoxList ID="chkListTable" runat="server" DataTextField="name" DataValueFeild="name" AutoPostBack="true" OnSelectedIndexChanged="chkListTable_SelectedIndexChanged"> </asp:CheckBoxList> </div> <div> <asp:CheckBoxList ID="chkListRow" runat="server" DataTextField="COLUMN_NAME" DataValueField="COLUMN_NAME" RepeatDirection="Horizontal"> </asp:CheckBoxList> </div>
aspx.cs
:protected void chkListTable_SelectedIndexChanged(object sender, EventArgs e) { tableName.Clear(); foreach (ListItem item in chkListTable.Items) { if(item.Selected) { tableName.Add(item.Text.Trim()); } } for(int i = 0; i < tableName.Count; i++) { String query = "USE " + dbname + " SELECT * FROM information_schema.columns" + " WHERE table_name = '" + tableName[i] + "'" + " AND COLUMN_NAME != 'rowguid'"; chkListRow.DataSource = Program.ExecSqlDataReader(query); chkListRow.DataBind(); Program.conn.Close(); } }
Program.cs
:public static bool Connect() { if (Program.conn != null && Program.conn.State == ConnectionState.Open) Program.conn.Close(); try { Program.conn.ConnectionString = Program.constr; Program.conn.Open(); return true; } catch (Exception e) { return false; } } public static SqlDataReader ExecSqlDataReader(String query) { SqlDataReader myreader; SqlCommand sqlcmd = new SqlCommand(query, Program.conn); sqlcmd.CommandType = CommandType.Text; if (Program.conn.State == ConnectionState.Closed) Program.conn.Open(); try { myreader = sqlcmd.ExecuteReader(); return myreader; myreader.Close(); } catch (SqlException ex) { Program.conn.Close(); return null; } }
I want my display to be like this:
[x]Table1 [x]Table2 [ ]Table3 [ ]Row1(Table1) [ ]Row2(Table1) [ ]Row3(Table1) [ ]Row1(Table2) [ ]Row2(Table2)
-
site only opens in CefSharp
zaakr.net is a site can be opened only in zaakr.exe application or through android(.apk), when opened in browser u been redirected to https://browser.zaakr.net so u download there application, (.exe) file is using cefsharp as a browser so it can access website, from 2 month i could open it from chromium as cefsharp uses chromium, now i can't access website through chromium for some reason idk, i even made a cefsharp browser myself using visual studio nothing worked all the time i been redirected to browser.zaakr.com, i want to access through any browser that have devtools available for a project, note that application zaakr.exe is still using cefsharp even the older version still can access site. i would appreciate any help, sry for any spelling mistakes, thanks.
-
C# MariaDB Update Function working in DataStore but not updating in .NET Application
My initial issue is that my database does not update when I call on this specific code. I am not sure if it is C# itself or the update query that I am calling.
string _connectionString = "validConnectionstring"; using (MySqlConnection _mySqlConnection = new MySqlConnection(_connectionString) { _mySqlConnection.Open(); using (MySqlCommand command = new MySqlCommand("UpdateProfileStatus", _mySqlConnection)) { command.Transaction = _mySqlConnection.BeginTransaction(); command.CommandTimeout = TimeSpan.FromSeconds(60).Seconds; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@_username", "test"); command.Parameters.AddWithValue("@_status", true); command.ExecuteNonQuery(); } _mySqlConnection.Close(); }
I get no updates in my database but my console logs that the query is executed returning the value of 1 but there is no update that actually happens in my DB. Is there something in my code to reason why it is failing?
Here is the stored procedure that I have for the update command
CREATE PROCEDURE UpdateProfileStatus(_username VARCHAR(25), _status BOOL) UPDATE Profile SET status = _status WHERE username = _username;
I know the Stored Procedure works but am not sure why my .NET application is not responding to my procedure call. Is it something to do with my implementation of the parameters or is it my procedure itself?
-
How to add a new Model visually in Mac OS visual Studio
I do not see any choice to create a model in Mac visual studio? I In the windows version the Class created with its imports
using Linq
using Threading.Tasks
using Collection.Generic
-
how to migrate global.asax event 'Application_Start' to program.cs on net.6?
I try to migrate an old projet with a console app and a webservice ( both on .net framework 4.6) to a .net 6 console app (I want to suppress the ws and just have a service). On the old webservice I have a global.asax with a usefull event 'Application_Start' : it let me initialise a static class used for data access (code is in vb.net but I move to c#)
Sub Application_Start(sender As Object, e As EventArgs) OldDLL.Initialisation(BmyEnum.Mode, My.Settings.mySCHEMAName) End Sub
I find various topics as (Migrate Global.asax to Startup.cs) on how to migrate from global.asax to Startup.cs but there is no more Startup.cs on my project generate by visualstudio2022, just a program.cs. Googleling a little bit I read that program.cs could replace startup.cs, using middleware. But I'm very new and it's a lot confusing. How I could in a simple way call OldDLL.Initialisation on program.cs ? Could be possible ( and how?) to embed my OldDll static on a service and inject it ? Thank you for reading, thank you for your suggestions.
-
Pass context with Hilt from ViewModel to data source
I'm trying to use Hilt to pass context along to my data source class, below:
public class PostDataSource extends PageKeyedDataSource<Integer, Post> { // we will start from the first page which is 1 public static final int PAGE_SIZE = 25; // we will start from the first page which is 1 private static final int FIRST_PAGE = 1; // this will be called once to load the initial data @Override public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull final LoadInitialCallback<Integer, Post> callback) { // I NEED TO CALL CONTEXT HERE } }
PostDataSource
has a data source factory:public class PostDataSourceFactory extends DataSource.Factory { //creating the mutable live data private MutableLiveData<PageKeyedDataSource<Integer, Post>> itemLiveDataSource = new MutableLiveData<>(); @Override public DataSource<Integer, Post> create() { //getting our data source object PostDataSource postDataSource = new PostDataSource(); //posting the datasource to get the values itemLiveDataSource.postValue(postDataSource); //returning the datasource return postDataSource; } //getter for itemlivedatasource public MutableLiveData<PageKeyedDataSource<Integer, Post>> getItemLiveDataSource() { return itemLiveDataSource; } }
And finally, here is the ViewModel class. This ViewModel is called from my fragment:
public class PostViewModel extends ViewModel { //creating livedata for PagedList and PagedKeyedDataSource public LiveData<PagedList<Post>> itemPagedList; LiveData<PageKeyedDataSource<Integer, Post>> liveDataSource; //constructor public PostViewModel() { //getting our data source factory PostDataSourceFactory postDataSourceFactory = new PostDataSourceFactory(); //getting the live data source from data source factory liveDataSource = postDataSourceFactory.getItemLiveDataSource(); //Getting PagedList config PagedList.Config pagedListConfig = (new PagedList.Config.Builder()) .setEnablePlaceholders(false) .setPageSize(PostDataSource.PAGE_SIZE).build(); //Building the paged list itemPagedList = (new LivePagedListBuilder(postDataSourceFactory, pagedListConfig)) .build(); } }
I don't understand how I would get context in
PostDataSource
using Hilt's dependency injection.I've tried doing something like this, but not really sure how to proceed:
public class PostDataSource extends PageKeyedDataSource<Integer, Post> { private Context context; @Inject PostDataSource(@ActivityContext Context context) { this.context = context; } ... }
-
cdi bean lack of value when accessed through public field
I have a configuration class, which I inject into another class.
Configuration class looks as follows:
@RequestScoped public class Configuration { @ConfigProperty(name = "VALUE") public String value; public String getValue() { return value; } }
This configuration is injected into the following place:
@ApplicationScoped public class EndpointImpl implements Endpoint { private Configuration configuration; @Inject public EndpointImpl(Configuration configuration) { this.configuration = configuration; System.out.println("configuration.value=" + configuration.value); System.out.println("configuration.getValue()=" + configuration.getValue()); System.out.println("configuration.value=" + configuration.value); }
Logs printed after going through constructor:
configuration.value=null
configuration.getValue()=someValue
configuration.value=null
I added postConstructor with the below similar code:
@PostConstruct public void postConstruct(){ System.out.println("configuration.value="+configuration.value); System.out.println("configuration.getValue()="+configuration.getValue()); System.out.println("configuration.value="+configuration.value); }
and the result is the same.
Everything works fine as long as the value is retrieved through the getter method. When I try to retrieve it through the public field it returns null. I thought that, when CDI completes the process of building the bean, the fields inside the class will be set to appropriate values.
Why does it behave in such a way?
-
"no main manifest attribute" in .jar Netbeans 13
I recently just started toying around with Maven in java. Time comes to test my project, it works fine in the NetBeans window, running the main class found in App.java (com.MyCompany.App), but when I try to run it from a command line I get an error:
"no main manifest attribute"
I'm using Apache Netbeans 13 with Maven to build the project
Any help will be apreciated Thanks in advance
-
Retrieve C# Attribute Data With Extension Method
Looking for a way to retrieve attribute data for a property on a class (many different types) in my data layer with an extension method...
Final goal is to see the method here and be able to access the properties:
I would expect to be able to do something like (non-working code):
Customer c = new Customer(); int mcl = c.CustNo.GetSchemaDetails().MaxCharLength;
The attribute is assigned to the class property as such:
public class Customer { [ColumnSchema("Customer", "CUST_NO")] public string CustNo { get; set; } //... }
I've created an extension method to retrieve the 'SchemaDetails' object from the 'ColumnSchemaAttribute'
public class AttributeExtensions { public static SchemaDetails GetSchemaDetails(Type T) { ColumnSchemaAttribute csa = (ColumnSchemaAttribute)Attribute.GetCustomAttribute(T, typeof(ColumnSchemaAttribute)); return csa.SchemaDetails; } }
Bulk of the 'ColumnSchemaAttribute' which returns db schema details for the column
public class ColumnSchemaAttribute : System.Attribute { private string tableName, columnName; public ColumnSchemaAttribute(string TableName, string ColumnName) { tableName = TableName; columnName = ColumnName; } private SchemaDetails schemaDetails; public SchemaDetails SchemaDetails { get { if (schemaDetails == null) { schemaDetails = getSchemaDetails(); } return schemaDetails; } } private SchemaDetails getSchemaDetails() { SchemaDetails sd = null; string sql = @" SELECT * FROM INFORMATION_SCHEMA.COLUMNS c LEFT JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu ON ccu.COLUMN_NAME = c.COLUMN_NAME and ccu.TABLE_NAME = c.TABLE_NAME LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ON tc.CONSTRAINT_NAME = ccu.CONSTRAINT_NAME and tc.TABLE_NAME = ccu.TABLE_NAME WHERE c.TABLE_NAME = @TableName and c.COLUMN_NAME = @ColumnName "; try { using (SqlConnection sqlConnection = new SqlConnection(Helper.GetConnectionString())) { sqlConnection.Open(); using (SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection)) { sqlCommand.CommandType = CommandType.Text; sqlCommand.Parameters.Add("@TableName", SqlDbType.NVarChar, -1).Value = tableName; sqlCommand.Parameters.Add("@ColumnName", SqlDbType.NVarChar, -1).Value = columnName; SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); while (sqlDataReader.Read()) { sd = readData(sqlDataReader); } } } } catch (Exception ex) { throw new System.ArgumentException(ex.Message); } return sd; } }
Any help regarding a way to do this or an alternative approach is very much appreciated.
-
woocommerce product variation color attributes on product list page redirect to single product page on-click
I want, when I click on these color attributes on the product list page it redirects me automatically to the single product page. it shows similar behavior to the title of the product. but I want this functionality only for the product list page, not for a single product page. please help thank you. enter image description here
-
Is it possible to switch Azure functions standard DI container for another?
Currently I am using DI in azure functions the standard way
public class Startup : FunctionsStartup { public override void Configure(IFunctionsHostBuilder builder) { /*Register dependencies*/ } }
(Microsoft.Azure.Functions.Extensions.DependencyInjection.FunctionsStartup)
Is it possible to switch to https://github.com/dadhi/DryIoc container while still being able to use DI to resolve dependencies through constructor of azure functions? If so, how? -
Extending Prism IContainerRegistry to register by name specifying constructor
I'm trying to migrate a Prism WPF application whitch is using Unity IoC container to use DryIoC container.
In a module I have the Unity container injected to register a class specifying the constructor.
unityContainer.RegisterType<IService, Service>( typeof(Service).FullName, new ContainerControlledLifetimeManager(), Invoke.Constructor( Resolve.Parameter<IDependency1>(), Resolve.Parameter<IDependency2>()... ));
I wanted to migrate this type of registers to use
IContainerRegistry
methods to register. I've seen thatIContainerRegistry
interface provides methods to regiser using Factory method whitch I can use to specify constructor, but there is no method with factory method as parameter and named register also.Does anybody have the same problem? Maybe extending the IContainerRegistry implementation?